ExceptionHandling_GL
  1. Java Exceptions
    1. What is Exceptional Handling
    2. Java Exception Hierarchy
  2. Java Try-Catch Block
  3. Java Multiple Catch Block
  4. Java Nested Try
  5. Java Finally Block
  6. Java Throw Keyword
  7. Java Throws Keyword

Java Exceptions

Exception handling plays an important role in Software Development. Most of the time it happens an exception is left unseen during code walkthroughs and testing. Exception handling helps in minimizing exceptions and helps in recovering from exceptions. It is one of the best mechanisms to handle runtime exceptions and makes our code error or bug-free. Exception handling helps in maintaining the flow of the program.

Java Tutorial for beginners

What is Exception Handling

An exception is an abnormal condition that may happen at runtime and disturb the normal flow of the program.

Let’s say 

<code>statement
statement
statement
exception ………… an exception occurred, then JVM will handle it and will exit the prog.
statement
statement
statement</code>

For handling exception, there are 2 possible approaches

exception handling in java

1.JVM

If an exception is not handled explicitly, then JVM takes the responsibility of handling the exception.

Once the exception is handled, JVM will halt the program and no more execution of code will take place

  • Example:
<code>import java.util.*;

class Main {
    public static void main (String[] args) {
        System.out.println(5/0);
        System.out.println("End of program!");
	}
}
</code>

Runtime Error:

 Exception in thread "main" java.lang.ArithmeticException: / by zero
 at Main.main(File.java:5) 

2.Developer

Developers can explicitly write the implementation for handling the exception. Once an exception is handled, the normal execution of code will continue.

Preferable: handle exceptions in order to ensure your code gets executed normally.

Java Exception Hierarchy

  Exception Hierarchy – Following is Java’s Exceptional handling hierarchy.

exception handling in java
  • Throwable – 
    • It is the root class for the exception hierarchy in java. 
    • It is in the java.lang package.
  • Error – 
    • Subclass of Throwable.
    • Consist of abnormal condition that is out of one’s control and depends on the environment
    • They can’t be handled and will always result in the halting of the program.
    • Eg: StackOverFlowError that can happen in infinite loop or recursion
  • Exception
    • Subclass of Throwable.
    • Consist of abnormal conditions that can be handled explicitly.
    • If one handles the exception then our code will continue to execute smoothly.
    • There are 2 major categories of exception
      • Checked Exceptions
        • Those exceptions that are checked at compile-time comprises checked exceptions.
        • They are child classes of Exception except for RuntimeException.
        • The program will not compile if they are not handled.
        • Example: IOException, ClassNotFoundException, etc.
      • Unchecked Exceptions
        • Those exceptions that are checked at runtime comprises unchecked exceptions.
        • They are child classes of RuntimeException.
        • They give runtime errors if not handled explicitly.
        • Example: ArithmeticException, NullPointerException etc.

Note the Entire hierarchy in java.lang package which is present by default in java programs and need not be explicitly imported.

Java Try-Catch Block

Basic syntax:

<code>
 try{
}
catch(Exception e){
}</code>
  • Example:
<code>public class ExceptionDemo {
	public static void main (String[] args) {
		int a=10;
		for(int i=3;i>=0;i--)
		   try{
		     System.out.println(a/i);  
		   }catch(ArithmeticException e){
		       System.out.println(e);
		   }
	}
}
</code>

Output:

3
5
10
java.lang.ArithmeticException: / by zero 
  • try block contains the code that might throw an exception. Don’t write anything extra in try as statements after the exception will not get executed if the exception occurred. Try must be immediately followed by catch or finally block.
<code>public class ExceptionDemo {
	public static void main (String[] args) {
		int a=10;
		for(int i=3;i>=0;i--)
		   try{
		     System.out.println(a/i);  
		   }
	}
}
</code>

Compile time error:

 prog.java:5: error: 'try' without 'catch', 'finally' or resource declarations
    try{
    ^
1 error 
  • The catch block is used to catch the exception thrown by statements in the try block. The catch must follow try else it will give a compile-time error.
<code>public class ExceptionDemo {
	public static void main (String[] args) {
		int a=10;
		for(int i=3;i>=0;i--)
		   try{
		     System.out.println(a/i);  
		   }
		   System.out.println("between try and catch");
		   catch(ArithmeticException e){
		       System.out.println(e);
		   }
	}
}

</code>

Compile Time Error:

 prog.java:5: error: 'try' without 'catch', 'finally' or resource declarations
    try{
    ^
prog.java:9: error: 'catch' without 'try'
    catch(ArithmeticException e){
    ^
2 errors 

Things to Remember

Do not keep any code after the statement which is prone to exception. Because if an exception occurred then it will straight away jump to the catch or finally block, ignoring all other statements in the try block.

<code>class Main {
	public static void main (String[] args) {
         try
       {
             System.out.println(4/0);
	 //will not get printed
             System.out.println("end of try!");
        }
catch(ArithmeticException e)
        {
            System.out.println("divide by 0");
        }
    }
}
</code>

Output:

divide by 0
  • While catching the exception in the catch block, either you can have directly the class of exception or its superclass.

Example: Exact Exception

<code>class Main {
	public static void main (String[] args) {
        try{
            System.out.println(4/0);
           }
      
        //ArithmeticException 
        catch(ArithmeticException e){
            System.out.println("divide by 0");
        }
    }
}
</code>

Output:

divide by 0

Example: Superclass of Exact Exception

<code>class Main {
	public static void main (String[] args) {
        try{
            System.out.println(4/0);
           }
      
        //superclass of ArithmeticException 
        catch(Exception e){
            System.out.println("divide by 0");
        }
     }
}
</code>

Output:

divide by 0

Java Multiple Catch Block

 If you have multiple catches, you have to maintain the hierarchy from subclass to superclass.

Incorrect:

<code>class Main {
	public static void main (String[] args) {
        try{
            System.out.println(4/0);
        }catch(Exception e)
        {
            System.out.println("Exception : divide by 0");
        }catch(ArithmeticException e)
        {
            System.out.println("ArithmeticException :divide by 0");
        }
	}
}
</code>

Compile time error:

 prog.java:11: error: exception ArithmeticException has already been caught
        }catch(ArithmeticException e)
         ^
1 error 

Correct:

<code>class Main {
	public static void main (String[] args) {
        try{
            System.out.println(4/0);
        }catch(ArithmeticException e)
        {
            System.out.println("ArithmeticException : divide by 0");
        }catch(Exception e)
        {
            System.out.println("Exception : divide by 0");
        }
   }
}
</code>

Output:

ArithmeticException: Divide by 0<br>

Java Nested Try

When there is another try block within the try block

<code>class Main {
	public static void main (String[] args) {
        try{
                try{
                    int[] a={1,2,3};
                    System.out.println(a[3]);
                }
   catch(ArrayIndexOutOfBoundsException e)
                {
                    System.out.println("Out of bounds");
                }
              System.out.println(4/0);
        }
       catch(ArithmeticException e)
        {
            System.out.println("ArithmeticException : divide by 0");
        }
	}
    }
</code>

Output:

 Out of bounds
ArithmeticException: Divide by 0 

Note: if we put code of outer try before inner try, then if an exception occurred, it will ignore the entire inner try and move directly to its catch block.


<code>class Main {
	public static void main (String[] args) {
        try{
               System.out.println(4/0);
               try{
                    int[] a={1,2,3};
                    System.out.println(a[3]);
                }
   catch(ArrayIndexOutOfBoundsException e)
                {
                    System.out.println("Out of bounds");
                }
        }
       catch(ArithmeticException e)
        {
            System.out.println("ArithmeticException : divide by 0");
        }
	}
    }
</code>

Output:

ArithmeticException: Divide by 0

Java Finally Block

Contains code that must be executed no matter if an exception is thrown or not. finally generally contains code of file release, closing connections, etc.

  • Working flow of finally:
exception handling in java
  • Example:
<code>class Main {
	public static void main (String[] args) {
        try{
            System.out.println(4/0);
        }catch(Exception e)
        {
            System.out.println(e);       
        }
        finally
        {
            System.out.println("finally executed");
        }
        
       	        System.out.println("end");
	}
}
</code>

Output:

 java.lang.ArithmeticException: / by zero
finally executed
end 

Finally will execute even when we do not handle exceptions. Before halting the program, JVM checks if there is finally block.

<code>class Main {
	public static void main (String[] args) {
        try{
            System.out.println(4/0);
            
        }finally
        {
            System.out.println("cleaning.......");
        }
	}
}

</code>

Runtime Error:

 Exception in thread "main" java.lang.ArithmeticException: / by zero
 at Main.main(File.java:4) 

Output:

cleaning.......

Java Throw Keyword

It is a keyword which is used to explicitly throw an exception

  • We can use throw where according to our logic an exception should occur.
  • Example:
<code>public class ExceptionDemo {
	static void canVote(int age){
		if(age<18)
            try{
                throw new Exception();
            }catch(Exception e){
                System.out.println("you are not an adult!");
            }
		else
		   System.out.println("you can vote!");
	}
	public static void main (String[] args) {
		canVote(20);
		canVote(10);
	}
}

</code>

Output:

you can vote!
you are not an adult! 

Java Throws Keyword

  • throws keyword is used when callee doesn’t want to handle the exception rather it wants to extend this responsibility of handling the exception to the caller of the function.
  • Basically says what sort of exception the code can throw and relies on the caller to handle it.
  • It is used to handle checked Exceptions as the compiler will not allow code to compile until they are handled.
  • Example:
<code>public class ExceptionDemo {
	static void func(int a) throws Exception{
		   System.out.println(10/a);  
	}
	public static void main (String[] args) {
		try{
		    func(10);
		    func(0);
		}catch(Exception e){
		   System.out.println("can't divide by zero");
		}
	
	}
}
</code>

Output:

1
can't divide by zero 


If callee can throw multiple exceptions, then all will be thrown simultaneously.

<code>import java.util.*;

public class ExceptionDemo {
	static void func(int a,int b) throws ArithmeticException, ArrayIndexOutOfBoundsException{
		   System.out.println(10/a); 
		   int[] arr={1,2,3};
		   System.out.println(arr[b]);
	}
	public static void main (String[] args) {
		Scanner in=new Scanner(System.in);
		for(int i=0;i<3;i++){
		try{
		    func(in.nextInt(),in.nextInt());
    		}catch(ArithmeticException e){
    		   System.out.println("can't divide by zero");
    		}catch(ArrayIndexOutOfBoundsException e){
    		   System.out.println("Out of bounds!");
    		}
		     }
		
	}
   }
</code>

Input:

2 1
0 1
2 3 

Output:

5
2
can't divide by zero
5
Out of bounds! 
  • Custom Exception: You can create your own exception and give implementation as to how it should behave. Your exception will behave like a child’s class of Exception.
  • Syntax:

class YourException extends Exception{}

  • Example:
    • let’s say, you are working with an airline company 
    • You are in the luggage check-in department and as per rules, you can allow 15kg per customer.
    • So now more than 15kg of weight is an abnormal condition for us or in other words its an exception
    • This is our logic-based exception, so we’ll create our custom exception WeightLimitExceeded 
    • As per syntax, it will extend Exception.
    • We define the constructor which will get invoked as soon as an exception will be thrown
    • We have to explicitly throw the exception and hence we will use throw keyword for that.
    • Using throws keyword is as per our need. If we are handling an exception where it is getting thrown then we can avoid throws, else we will use throws and handle it in the caller.
    • Implementation:
<code>import java.util.*;

class WeightLimitExceeded extends Exception{
    WeightLimitExceeded(int x){
        System.out.print(Math.abs(15-x)+" kg : ");
    }
}


class Main {
    void validWeight(int weight) throws WeightLimitExceeded{
        if(weight>15)
            throw new WeightLimitExceeded(weight);
        else
            System.out.println("You are ready to fly!");
    }
    
      public static void main (String[] args) {
        Main ob=new Main();
        Scanner in=new Scanner(System.in);
        for(int i=0;i<2;i++){
            try{
                ob.validWeight(in.nextInt());
            }catch(WeightLimitExceeded e){
                System.out.println(e);
            }
        }
        
	}
}
</code>

Input:

20
7 

Output:

 5 kg : WeightLimitExceeded
You are ready to fly! 

This brings us to the end of this article where we learned about exception handling in java. To get a free course about java, click the banner below.

exception handling in java
0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

thirteen − 7 =