Customized exception handling in java
In this tutorial, we will discuss customized exception handling using a try-catch. Here we will show how to handle the exception with and without try-catch.
Case I: Without try-catch
Without try-catch, the Default exception handler is responsible to terminate the program abnormally and print the exception message to the console. The below demo example provide a clear description of how to handle exception without using a try-catch block.
Example:
package com.navneet.javatutorial;
public class DefaultExceptionHandling {
public static void main(String[] args) {
m1();
}public static void m1(){
m2();
System.out.println("Hello World");}
public static void m2(){System.out.println(10/0);
}}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.navneet.javatutorial.DefaultExceptionHandling.m2(DefaultExceptionHandling.java:18)
at com.navneet.javatutorial.DefaultExceptionHandling.m1(DefaultExceptionHandling.java:12)
at com.navneet.javatutorial.DefaultExceptionHandling.main(DefaultExceptionHandling.java:8)
Case II: With try-catch block
Exception handling is the process of providing an alternative way to continue the rest of the program normally without losing any resources used in the program. The below demo example provide a clear description of how to customized exception using a try-catch block.
Output:
Catch block statement is here
Method m2 statement
Hello World