Understanding Try and Catch Blocks in Java: A Comprehensive Guide

Rumman Ansari   Software Engineer   2024-07-04 04:48:07   7341  Share
Subject Syllabus DetailsSubject Details 4 Questions
☰ TContent
☰Fullscreen

Table of Content:

Java exception handling is managed via five keywords

  1. try,
  2. catch,
  3. throw,
  4. throws, and
  5. finally.

Java try block

Try is used to guard a block of code in which exception may occur. This block of code is called guarded region. A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception.A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.


Java try block must be followed by either catch or finally block.

Syntax of java try-catch

try{  
//code that may throw exception  
}catch(Exception_class_Name ref){}  

Syntax of try-finally block

try{  
//code that may throw exception  
}finally{}  

general form of an exception-handling block:

try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
} 

Here, ExceptionType is the type of exception that has occurred. The remainder of this chapter describes how to apply this framework.

Problem without exception handling

Let's try to understand the problem if we don't use try-catch block.

public class trycatch{
  public static void main(String args[]){
      int data=50/0;//may throw exception
      System.out.println("rest of the code...");
  }
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at trycatch.main(trycatch.java:3)
Press any key to continue . . .

As displayed in the above example, rest of the code is not executed (in such case, rest of the code... statement is not printed). There can be 1000 lines of code after exception. So all the code after exception will not be executed.

Solution by exception handling

Let's try to understand the problem if we don't use try-catch block.

public class trycatch{
  public static void main(String args[]){
   try{
      int data=50/0;
   }catch(ArithmeticException e){
	   System.out.println(e);
	   }
   System.out.println("rest of the code...");
 }
}
java.lang.ArithmeticException: / by zero
rest of the code...
Press any key to continue . . .

Solution by exception handling example

class Excptn
{
 public static void main(String args[])
 {
  int a,b,c;
  try
  {
   a=0;
   b=10;
   c=b/a;
   System.out.println("This line will not be executed");
  }
  catch(ArithmeticException e)
  {
   System.out.println("Divided by zero"); 
  }
  System.out.println("After exception is handled");
 }
}
Divided by zero
After exception is handled
Press any key to continue . . .

An exception will thrown by this program as we are trying to divide a number by zero inside try block. The program control is transferred outside try block. Thus the line "This line will not be executed" is never parsed by the compiler. The exception thrown is handled in catch block. Once the exception is handled, the program control is continue with the next line in the program i.e after catch block. Thus the line "After exception is handled" is printed.