Java Try Catch Block

In Java, try-catch block is used for exception handling. Allowing us to handle and manage runtime exceptions. The try block’s remaining statements won’t run if an exception arises at that specific statement. Therefore, it is advised against keeping code in a try block that won’t throw an exception.

Java try blocks must be followed by a finally block or a catch.

The basic structure of the try-catch block will look like this:

try {
// block of code to try
   } 
catch (Exception e1) {
// block of code to handle errors
    }

Try block

  • The try block allows us to define a block of code that you want to monitor for exception.
  • If an exception occurs within this block, the control will be transferred to the appropriate catch block.

Catch block

  • The particular sort of exception is caught and handled using the catch block.
  • We can use multiple catch blocks within a try block.
  • It is used to handle different types of exceptions within the try block.
try {
// block of code to try
}
catch(exception e1 {
// block of code to be handle
}
catch(Exception e2)
{
// block of code to be handle
}

Catch block

Blocks and Exception Handling Keywords

try:

There are a number of statements in the try block where an exception might arise.

try
// Statement(s) that could lead to an exception

catch:

The catch block is used to manage a try block’s ambiguous condition. A catch block, which deals with the exception that arises in the related try block, is always placed after a try block.

close a connection, close a file, and leave the process after writing details to a log file are some instances of catch statements that handle exceptions.

throw:

Control is moved from the try block to the catch block using the throw keyword.

throws:

When handling exceptions without the use of a try-and-catch block, this keyword is used. It does not handle the exceptions that a method can throw to the caller; it only specifies them.

finally:

It is carried out following the catch block. When there are several catch blocks, we use it to place some common code (to be performed whether an error has happened or not).

Example

public class DataFlair
{
    public static void main(String[] args) {
        try{
        int data = 10/0;
        System.out.println(data);
        }
        catch(Exception e){
            System.out.println("Something went wrong");
        }
            
        }
        
    }

Output

Something went wrong

In this example, the divide method attempts to divide two integers. Since division by zero is not allowed, an ArithmeticException is thrown. The try-catch block catches this exception and prints an error message, and the finally block prints a message indicating its execution.

In Java, a try block can be used in place of a catch block. But without a try block, we are unable to employ a catch block.

Internal Working of Java try-catch block:

Internal-Working-of-Java

Problem without Exception Handling

Example 1

public class TryCatchExample1 {  
    public static void main(String[] args) {      
        int data=50/0; 
        System.out.println("rest of the code");     
    }     
}

Output

Exception in thread “main” java.lang.ArithmeticException: / by zero

The remaining statements in the code are not printed in this scenario, and the remaining code is not run. 100 lines of code could follow the exception. The code below the exception will not run if the exception is not handled.

Solution by Exception Handling

Example 2

public class TryCatchExample2 { 
    public static void main(String[] args) {  
        try  
        {  
        int data=50/0; //may throw exception   
        }  
        catch(ArithmeticException e)  
        {  
            System.out.println(e);  
        }  
        System.out.println("rest of the code");  
    }  
}

Output

java.lang.ArithmeticException: / by zero

rest of the code

The remaining code is executed, resulting in the printing of the remaining code statement, as seen in the example above.

Java try…..catch block:

Example

class Main {
  public static void main(String[] args) {
    try {
      int divideByZero = 5 / 0;
      System.out.println("Rest of code in try block");
    }
    catch (ArithmeticException e) {
      System.out.println("ArithmeticException => " + e.getMessage());
    }
  }
}

Output

ArithmeticException => / by zero

We are attempting a division by zero of an integer. There is an exception in this situation. The try block is where we have placed this code as a result. ArithmeticException happens whenever this code is seen by the program. Additionally, the catch block executes the code inside it after catching the exception. Only when there is an exception in the try block is the catch block actually used.

Java try….finally block

Example

class Main {
  public static void main(String[] args) {
    try {
      int divideByZero = 5 / 0;
    }
    finally {
      System.out.println("Finally block is always executed");
    }
  }
}

Output

Finally block is always executed

Exception in thread “main” java.lang.ArithmeticException: / by zero

at Main.main(Main.java:4)

Together with the finally block, we have used the try block. We can see that the try block’s code is resulting in an exception. However, regardless of the exception, the code inside the finally block is run.

Conclusion

A try block is a section of code that comprises a number of statements and is used to contain any code that could raise an exception. The catch block, which deals with the exception that arises in the related try block, is always placed after the try block.