Java try and catch usage <br /> Although the default exception handler provided by the Java runtime system is useful for debugging, you usually want to handle exceptions yourself. There are two benefits to doing this. First, it allows you to fix errors. Second, it prevents the program from automatically termination. Most users are upset (to say the least) about printing stack tracks when the program terminates and whenever an error occurs. Fortunately, this is easy to avoid.
To prevent and handle a runtime error, you just need to put the code you want to monitor into a try block. Following the try block, including a catch clause that specifies the type of error you want to catch. It is very simple to complete this task. The following program contains a try block and a catch clause that handles the ArithmeticException exception generated by dividing it by zero.
class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After c atch statement."); }} The program outputs as follows:
Division by zero.After catch statement.
Note that the call to println( ) in the try block is never executed. Once the exception is raised, the program control is transferred from the try block to the catch block. Execution never "returns" from the catch block to the try block. So, “This will not be printed.”
Will not be displayed. Once the catch statement is executed, program control continues from the following line of the entire try/catch mechanism.
A try and its catch statement form a unit. The scope of the catch clause is limited to the statement defined before the try statement. A catch statement cannot catch the exception raised by another try statement (unless it is a nested try statement case).
Statements protected by try must be within a brace (that is, they must be in a block). You can't use try alone.
The purpose of constructing a catch clause is to resolve exceptions and continue to run as if the error did not occur. For example, in the following program, each for loop is repeated to obtain two random integers. These two integers are divided by the other party respectively, and the result is used to divide 12345. The final result exists in a. If a division operation results in a zero division error, it will be captured, the value of a is set to zero, and the program continues to run.
// Handle an exception and move on.import java.util.Random;class HandleError { public static void main(String args[]) { int a=0, b=0, c=0; Random r = new R andom() ; for(int i=0; i<32000; i++) { try { b = r.nextInt(); c = r.nextInt(); a = 12345 / (b/c); } catch (ArithmeticException e) { System.out.println("Division by zero."); a = 0; // set a to zero and continue } System.out.println("a: " + a); } }}Show an exception description
Throwable overloads the toString( ) method (defined by Object), so it returns a string containing the exception description. You can display the description of the exception by passing a parameter to the exception in println( ). For example, the catch block of the previous program can be rewritten as
catch (ArithmeticException e) { System.out.println("Exception: " + e); a = 0; // set a to zero and continue} When this version replaces the version in the original program, the program runs under the standard javaJDK interpreter, and each error is divided by zero displays the following message:
Exception: java.lang.ArithmeticException: / by zero
Although there are no special values in the context, the ability to display an exception description is valuable in other cases - especially when you experiment and debug an exception.
Use of Java Multiple Catch Statement <br />In some cases, multiple exceptions may be caused by a single code segment. To handle this situation, you can define two or more catch clauses, each of which catches an exception of one type. When an exception is raised, each catch clause is checked in sequence, and the first clause matching the exception type is executed. When a catch statement is executed, other clauses are bypassed, and execution continues from the code after the try/catch block. The following example designs two different exception types:
// Demonstrate multiple catch statements.class MultiCatch { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a ; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsExcep tion e) { System.out .println("Array index oob: " + e); } System.out.println("After try/catch blocks."); }}The program runs in the starting condition without command line parameters resulting in a zero-divided exception because a is 0. If you provide a command line parameter, it will survive, setting a to a value greater than zero. But it will cause the ArrayIndexOutOf BoundsException exception because the integer array c is 1 in length and the program tries to assign a value to c[42].
Here is the output of the program running in two different situations:
C:/>java MultiCatcha = 0Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks.C:/>java MultiCatch TestArga = 1Array index oob: j ava.lang.ArrayIndexOutOfBoundsException After try/catch blocks.
When you use a multi-catch statement, it is important to remember that exception subclasses must be used before any of their parent classes. This is because using the catch statement of the parent class will catch exceptions for the type and all its subclass types. This way, if the subclass is behind the parent class, the subclass will never arrive. Moreover, the code that cannot be reached in Java is an error. For example, consider the following procedure:
/* This program contains an error.A subclass must come before its superclass in a series of catch statements. If not,unreachable code will be created and acompile-t ime error will result.*/class SuperSubCatch { public static void main(String args []) { try { int a = 0; int b = 42 / a; } catch(Exception e) { System.out.println("Generic Exception catch."); } /* This catch is never reached because A rithmeticException is a subclass of Exception. */ catch(ArithmeticException e) { // ERROR - unreachable System.out.println("This is never reached."); } }}If you try to compile the program, you will receive an error message that the second catch statement will not arrive because the exception has been caught. Because ArithmeticException is a subclass of Exception, the first catch statement will handle all Exception-oriented errors, including ArithmeticException. This means that the second catch statement will never be executed. To modify the program, reverse the order of the two catch statements.