Java try block

Java try block is used to enclose the statements in the program which might throw an exception. Java try block must be followed by a catch block or finally block to handle the exceptions that are occurred in try block.

Note: try block must be used within method.

Syntax of the try block.

try { statement 1; // the code that might throw an exception } catch(Exception e) { }

Internal working of java try-catch block

As we have discussed earlier that when we do not use try-catch block in our program then we are not able to maintain the normal flow of execution of our program in result of which our program terminates when there occurs an exception thus escaping rest of the statements in a program from where exception occurs. Let’s understand through the example.

Problem without try-catch block in java

class Without_try_catch { public static void main(String args[]) { int a; a=50/0; System.out.println("Problem without try-catch block"); }
}

Output:

Without try-catch block
Note: In the above program rest of the code is not executed from where exception occurs

Solution of exception handling problem using try and catch block.

class Try_Catch_Demo { public static void main(String args[]) { int a; try { a=50/0; }catch(ArithmeticException e) { System.out.println(e); } System.out.println("Exception handling is implemented"); System.out.println("Thus,Rest of the code is executed"); }
}

Output:

Solution to problem using exception handling
Note: Here rest of the statements are executed from where exception occurs.

One can also handle the exception using its Parent class.

Let’s see an example to handle the exception using parent class

class Try_Catch_Demo
{
public static void main(String args[])
{
int a;
try
{
a=50/0;
}catch(RuntimeException e)
{
System.out.println(e);
}
System.out.println(“Exception handling is implemented”);
System.out.println(“Thus,Rest of the code is executed”);
}
}

Output:

See the below diagram minutely.

Note: If an exception occurs then the specific exception can be handled by the specific class or by its immediate parent class. In the above example ArithmeticException occurs therefore in catch block it can be handled by its specific class such as ArithmeticException class or its immediate parent class i.e. RuntimeException class or its immediate parent Exception class or its immediate parent Throwable class. For more information see Java class hierarchy in previous page.