I've got a strange problem with my program. I wrote the following code:
class Divide{
int a, b;
int divide(int a, int b) {
try {
if (b > 1)
throw new ArithmeticException("Generating exception");}
catch (ArithmeticException e) {
System.out.println("Caught exception 1st time" + e);
throw e;
}
int c = a / b;
return c;
}
}
And after that I wanted to do exception handling
and get variable from it in following way:
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Divide d = new Divide();
int result = 0;
try
{
result = d.divide(12, 2);
} catch (ArithmeticException e)
{
System.out.println("2 raz");
}
System.out.println(result); ///getting 0 insted of 6!
}
}
And i am still getting varible before try-catch block. How can I do this type of exception handling and get the varible with value after use of divade method.
Since you throw an exception whenever b is larger than 0, an exception is thrown when you run it with a value of 2. Thus, result is never updated, and 0 is displayed at the end of your program.
To obtain the correct output you will need to change your if statement in the divide method to not throw an exception any time b is greater than 1.
Inside catch with throw e; you rethrow an already caught error.
This is why this
int c = a / b;
is not executed.
If you remove
throw e;
you will get 6 as a result.
Related
This question already has an answer here:
Stack trace is not printed in proper order with other messages on console
(1 answer)
Closed 4 years ago.
I find an interesting case:
public static void main(String[] args) {
int a =0;
int b = 2;
int c = 10;
int d = 0;
int e = 0;
try {
d=c/b;
e=b/a;
}catch (ArithmeticException ex){
System.out.println("TEST");
ex.printStackTrace();
}
System.out.println(d);
}
There will be two kinds of printing order:
1
TEST
java.lang.ArithmeticException: / by zero
at Chapter10.Test2.main(Test2.java:14)
5
2
java.lang.ArithmeticException: / by zero
at Chapter10.Test2.main(Test2.java:14)
TEST
5
But when I comment the line System.out.println("TEST");,there will be only one order:
5
java.lang.ArithmeticException: / by zero
at Chapter10.Test2.main(Test2.java:14)
So I want to ask what's the order of the executed order of try-catch block? Why is the System.out.println(d); executed before catch block when the exception happens?
printStackTrace writes to System.err, which is a diifferent stream than System.out. Change your code to ex.printStackTrace(System.out) for a consistent output.
public static void main(String[] args) {
int a =0;
int b = 2;
int c = 10;
int d = 0;
int e = 0;
try {
d=c/b;
e=b/a;
}catch (ArithmeticException ex){
System.out.println("TEST");
ex.printStackTrace(System.out);
}
System.out.println(d);
}
Will yield
TEST
java.lang.ArithmeticException: / by zero
at Chapter10.Test2.main(Test2.java:18)
5
As expected.
you nead to use with "System.out" instead of "printStackTrace()".
By default, Exception.printStackTrace() uses System.err as PrintStream, which is not the same with System.out. So the order of code execution:
System.out.println("TEST");
ex.printStackTrace();
System.out.println(d);
might be inconsistent with the actual output. For certain, 5 will be printed after TEST. The exception message might be printed:
before TEST
between TEST and 5
after 5.
I created the below code for understanding purpose.
In below code there is an error in try block so it should go to catch block and print 15 also as finally block is always executed we should also get 20.
But in the output I am getting only 20 and not 15 in the output.
Kindly advise how why there is this descripancy.I am a begineer in Java.
Also make any necessary changes in the program if needed to get both 15 and 20 as output.
package javaapplication91;
public class NewClass
{
public static void main(String[] args)
{
NewClass n = new NewClass();
int z = n.m1();
System.out.println("z = " + z);
}
public int m1()
{
try
{
int a = 10/0;
System.out.println("Exception created");
return 10;
}
catch(ArithmeticException ae)
{
return 15;
}
finally
{
return 20;
}
}
}
You can return only one value from method if your method declaration return value type is int.
When you cath exception ArithmeticException you try to return 15, but you got 20, because finally block execute allways in the end of try catch block and it would be last return statement.
You can read about finally here (Java Tutorial)
If you want return both values, you can use array or list like this:
public List<Integer> m1() {
List<Integer> returnValues = new ArrayList<Integer>();
try {
int a = 10/0;
System.out.println("Exception created");
returnValues.add(10);
} catch(ArithmeticException ae) {
returnValues.add(15);
} finally {
returnValues.add(20);
return returnValues;
}
}
The return inside the ArithmeticException will be overridden by the finally return and that will be returned to your function.
Advice is , finally can be used only when closing a file or recovering resources.
I'm learning try and catch exception with java and I have some problems. Indeed, I have setup ArithmeticException catch & try but the exception is not catch in some cases...
My Recursion.java :
import java.lang.ArithmeticException;
public class Recursion {
private int u0;
private int u1;
public Recursion(int u0, int u1) {
this.u0 = u0;
this.u1 = u1;
}
public int boucle (int n) throws ArithmeticException{
switch (n) {
case 0 :
return this.u0;
case 1 :
return this.u1;
}
try{
if ( (n%2) == 0 ) {
return (boucle(n-1) / boucle(n-2)) - (boucle(n-2) / boucle (n-1));
}
else{
return (boucle(n-2) / boucle(n-1)) - (boucle(n-1) / boucle (n-2));
}
}
catch (ArithmeticException e){
System.out.println("Erreur division par 0 !");
throw e;
}
}
}
My Main.java :
public class Main {
public static void main(String[] args){
Recursion monObjet1 = new Recursion (100,2);
Recursion monObjet2 = new Recursion (100,1);
System.out.println(monObjet2.boucle(10));
}
}
I obtain this :
Erreur division par 0 !
Erreur division par 0 !
Erreur division par 0 !
Erreur division par 0 !
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Recursion.boucle(Recursion.java:32)
at Recursion.boucle(Recursion.java:32)
at Recursion.boucle(Recursion.java:32)
at Recursion.boucle(Recursion.java:28)
at Main.main(Main.java:11)
I dont understand why the exception is not catch...
Some of the output code may be in French I apologize for the inconvenience...
Best Regards,
Astrus
The exception is catched as you can see in your console. But it is thrown again by throw e;. If you delete it no stack trace will be written to the console.
You're not catching it in your main method anymore (unlike the other methods where you catch and rethrow it). It will then be thrown out of the main method and be handled by the default exception handler for that thread, resulting in printing the full stacktrace of the exception.
Add a try-catch to your main method and don't rethrow the exception to avoid printing of the stacktrace.
This line
throw e;
Throws your exception outside of boucle method into main. You need to catch this exception in your main method.
Just remove try-catch from boucle method and put in main method.
import java.lang.ArithmeticException;
class Recursion {
private int u0;
private int u1;
public Recursion(int u0, int u1) {
this.u0 = u0;
this.u1 = u1;
}
public int boucle(int n) throws ArithmeticException {
switch (n) {
case 0:
return this.u0;
case 1:
return this.u1;
}
if ((n % 2) == 0) {
System.out.println("if " + (n - 1));
return (boucle(n - 1) / boucle(n - 2))
- (boucle(n - 2) / boucle(n - 1));
}
else {
System.out.println("else" + (n - 1));
return (boucle(n - 2) / boucle(n - 1))
- (boucle(n - 1) / boucle(n - 2));
}
}
public static void main(String[] args) {
Recursion monObjet1 = new Recursion(100, 2);
Recursion monObjet2 = new Recursion(100, 1);
try {
System.out.println(monObjet2.boucle(10));
} catch (ArithmeticException e) {
System.out.println("Erreur division par 0 !");
}
}
}
This is my first time using exception handling so be gentle. I have a simple blob class that accepts an ID, the id must be between 30 and 50 or else an exception is thrown.
public class Blob {
int id;
public Blob() {
}
public Blob(int id) throws Exception {
this.id = id;
if (id < 30 || id > 50)
throw new Exception ("id = " +id+ ", must be between 30 and 50 inclusive");
}
}
It should prompt the user to enter an id, and throw the exception if it's not between 30 and 50, and should continue until the user enters a valid input and then simply displays the id number.
public class BlobCreator {
public static void main(String[] args) {
int id;
Scanner scan = new Scanner(System.in);
System.out.println("Enter ID number: ");
id = scan.nextInt();
do {
try {
Blob b = new Blob(id);
}
catch (Exception e) {
System.out.println(e);
}
System.out.println("Enter a different ID: ");
id = scan.nextInt();
}
while(true);
}
System.out.println("Blob ID: " +id);
}
I think that I am using the throw and catch correctly, but my loop isn't working correctly so I think that should be a simple fix but I can't get it just right. Also is using a while loop like I have the best way for this situation or is there a better way to loop through throw and catch?
Thanks for any and all help
You should place the break; after the code is executed successfully.
do {
try {
Blob b = new Blob(id);
break;
}
catch (Exception e) {
System.out.println(e);
}
System.out.println("Enter a different ID: ");
id = scan.nextInt();
} while(true);
So each time the loop would reach the end of its body, it would break out of the loop. You only should break after the blob is created successfully. Although I dont see why you put a break anyway. The while loop can check if the entered input was valid and simply stop the loop.
I modified the while in a do-while loop... By using true the loop will run forever, unless no exception is thrown by the constructor... This makes the code more generic (if you modify the conditions of the blob-construction, you don't have to modify the condition of the while loop).
Sorry, its kind of late to the party. Hope users who endup here may find this useful.
The use of break keyword is discouraged
Here is a very simple implementation to break away after implementing a retry mechanism
This iterates over the loop for the specified number of times and also if the exception still persists, then the exception is thrown. This can be leveraged for an actual real world scenario where the resttemplate might actually result in IO/Network errors and can be retried in those cases
public class TestClass {
public static void main(String[] args) throws Exception {
try {
int c = anotherM();
System.out.println("Now the value is" + c);
} catch (Exception e) {
System.out.println("Inside" + e);
}
}
public static int anotherM() throws Exception {
int i = 4;
Exception ex = null;
while (i > 0) {
try {
System.out.println("print i" + i);
throw new IOException();
// return i;
} catch (Exception e) {
System.out.println(e);
i--;
if (i == 1) {
ex = new Exception("ttt");
}
}
}
if (ex != null) {
throw new Exception("all new");
} else {
return i;
}
}
}
I hava a method called test() that throws an exception.
I want to write a loop that executes as long as it throws an exception, and breaks when it no longer throws an exception.
Can any one hint me on the logic that must be use?
For example I tried,
int i=0;
while(test())
{
i++;
}
System.out.println(i);
int i=0;
while (true) {
try {
test();
break;
} catch (Exception e) {
i++; // Loop will continue
}
}