try and catch in java

In Java, the try and catch blocks are used together for exception handling. Here’s a brief explanation:

  1. Try Block:
  • The try block contains a set of statements that might generate an exception.
  • It encloses the code that needs to be monitored for exceptions.
   try {
       // code that may throw an exception
   }
  1. Catch Block:
  • The catch block follows the try block and specifies the type of exception it can handle.
  • If an exception of the specified type occurs in the try block, the corresponding catch block is executed.
   try {
       // code that may throw an exception
   } catch (SomeExceptionType e) {
       // code to handle the exception
   }

You can have multiple catch blocks to handle different types of exceptions.

   try {
       // code that may throw an exception
   } catch (SomeExceptionType1 e) {
       // code to handle exception type 1
   } catch (SomeExceptionType2 e) {
       // code to handle exception type 2
   } catch (Exception e) {
       // generic catch block for any other exception type
   }

Here’s a simple example:

public class Example {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0); // This may throw an ArithmeticException
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.err.println("Caught an arithmetic exception: " + e.getMessage());
        }
    }

    static int divide(int a, int b) {
        return a / b;
    }
}

In this example, the divide method is called with arguments that may cause an ArithmeticException. The exception is caught in the catch block, and an error message is printed. It’s essential to handle exceptions to prevent unexpected program termination and provide graceful error recovery.

try block. Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch

Example of try and catch

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 catch statement.");
}
}

Output of try and catch

Division by zero.
After catch statement.

Inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block. Put differently, catch is not “called,” so execution never “returns” to the try block from a catch. Thus, the line “This will not be printed.” is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism

Nested try Statements

The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception

Example of nested try statements

class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}

Output

C:>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

Leave a Comment