DEV Community

jana009
jana009

Posted on

Exception Handling

Hi Guys,

In programming, lots of time we face errors. As a programmer we need to know how to handle those unexpected scenario in a best way so that's why we are going to see about Exception Handling

Exception:

Exception is an unwanted or unexpected situation which causes the program to terminate abnormally.

Default Exception Handler:

When executing the program if an exception occurs then the method in which the exception created is responsible to create the Exception Object.The Exception Object Contains 3 information

  • Name of the Exception
  • Description of the Exception
  • Stack trace(provide the information from which method and which line exactly the error occurs) and handover this object to the JVM(Java Virtual Machine).

Then JVM gives the object to Default Exception Handler and terminates the program abnormally without executing rest of the lines.

Example with no Exception:

public class ExcepExample{
    public static void main(String args[]){

        int num=10/2;
        System.out.println("Print the A Value  "+num);
        System.out.println("End of the Program! ");

    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Without Exception

Example with Exception

public class ExcepExample{
    public static void main(String args[]){

        int num=10/0;
        System.out.println("Print the A Value  "+num);
        System.out.println("End of the Program! ");

    }
}
Enter fullscreen mode Exit fullscreen mode

Output

With Exception

In Example Without Exception the program runs successfully and we got the output but in the Example with Exception the program terminates abruptly without executing the rest of the lines and prints the details of the Exception ArithmeticException.
In above exception exception example
ArithmeticException => Name of the Exception
/ by zero => Description of the Exception
at ExcepExample.main(ExcepExample.java:4) => Is the stack trace.

So as programmer we need to handle this scenario and make program to terminate in normal way.

For that will use try...catch

Try...Catch

Syntax

try{
//code Which cause the Exception
}Catch(Exception ex){
// Customize the how to display the exception
}

Example

public class ExcepExample{
    public static void main(String args[]){

        try{
                int num=10/0;
                System.out.println("Print the A Value  "+num);
        }catch(ArithmeticException ex){
            ex.printStackTrace();
       }

        System.out.println("End of the Program! ");

    }
}
Enter fullscreen mode Exit fullscreen mode

Output

try...catch

Top comments (0)