Java try catch block

By | March 18, 2022
Java try catch block

The try is a keyword that is used by java to enclose the code that might throw an exception. You can use the try block within the method body. It is recommended to keep that code in the try block only that will throw an exception. Also, the try block must always be followed by the catch and the finally block.

Syntax of Java try-catch

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

Syntax of try-finally block

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

Java Catch block

The catch block will allow you to handle the thrown exception by declaring the type of exception raised within the parameter of the catch block. It is a better way to declare the exception of the generated type to avoid the error. This catch block must be used after the try block and you can declare as many catch block as possible.

Example without Exception handling-

import java.util.regex.*;  
public class Simple{  
public static void main(String args[]){  
      int data=100/0;  
  }  
}

Output

Vamware

Example without Exception handling

Example with exception handling-

Vamware
import java.util.regex.*;  
public class Simple{  
public static void main(String args[]){  
try{  
      int data=100/0;  
  }  
catch(ArithmeticException e)  
       {  
            System.out.println(e);  
        }  
        System.out.println("code");  
    }  
}

Output-

Example with exception handling

Internal working of the try-catch block-

JVM checks for the raised exception is being handled or not. If in case the exception is not handled then JVM allows you to provide the default exception handler that will perform the below-mentioned task-

  • Display the description of the raised exception.
  • It will also display the stack trace to define the hierarchy of methods where the exception occurred.
  • Terminates the program from that step from where the exception is raised.

But if in case the exception is handled then the normal flow of the program will be continued and the remaining code will get executed.

Vamware

People are also reading: 

Author: Ramya Shankar

A cheerful, full of life and vibrant person, I hold a lot of dreams that I want to fulfill on my own. My passion for writing started with small diary entries and travel blogs, after which I have moved on to writing well-researched technical content. I find it fascinating to blend thoughts and research and shape them into something beautiful through my writing.

Leave a Reply

Your email address will not be published.