Java try catch block

Posted in /  

Java try catch block
ramyashankar

Ramya Shankar
Last updated on July 21, 2024

    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

    Example without Exception handling

    Example with exception handling

    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.

    People are also reading:

    Leave a Comment on this Post

    0 Comments