Exception Handling in Java with Examples | 2023

0
151
Exception Handling in Java with Examples | 2023


Exception dealing with in java is without doubt one of the highly effective mechanisms to deal with runtime errors brought on by exceptions. Exception dealing with performs an vital function in software program growth. This article helps you perceive java exception, exception in java, java exception dealing with, java exception hierarchy, kinds of exception in java, and lots of extra.

What is Exception Handling in Java?

Exception dealing with in java helps in minimizing exceptions and helps in recovering from exceptions. It is without doubt one of the highly effective mechanisms to deal with runtime exceptions and makes it bug-free. Exception dealing with helps in sustaining the move of this system. An exception dealing with is outlined as an irregular situation that will occur at runtime and disturb the traditional move of this system.

Also Read: Java Tutorial for freshmen

What is an Exception?

An expectation is an sudden occasion that happens whereas executing this system, that disturbs the traditional move of the code.

Exception dealing with in java with an instance:

Let’s say,

assertion
assertion
assertion
exception ………… an exception occurred, then JVM will deal with it and can exit the prog.
assertion
assertion
assertion

For dealing with exceptions, there are 2 potential approaches

1. JVM

If an exception shouldn’t be dealt with explicitly, then JVM takes the accountability of dealing with the exception.

Once the exception is dealt with, JVM will halt this system and no extra execution of code will happen

import java.util.*;

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

Runtime Error:

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

2. Developer

Developers can explicitly write the implementation for dealing with the exception. Once an exception is dealt with, the traditional execution of code will proceed.

Preferable: deal with exceptions to make sure your code will get executed usually.

Java Exception Hierarchy

Exception Hierarchy – Following is the Exception Handling in Java dealing with hierarchy.

  • Throwable
    • It is the basis class for the exception hierarchy in java. 
    • It is within the java.lang bundle.
  • Error
    • Subclass of Throwable.
    • Consist of irregular situation that’s out of 1’s management and relies on the surroundings
    • They can’t be dealt with and can all the time consequence within the halting of this system.
    • Eg: StackOverFlowError that may occur in infinite loop or recursion
  • Exception
    • Subclass of Throwable.
    • Consist of irregular situations that may be dealt with explicitly.
    • If one handles the exception then our code will proceed to execute easily.

Types of exception in Java

  • Checked Exceptions
    • Those exceptions which might be checked at compile-time includes checked exceptions.
    • They are youngster courses of Exception aside from RuntimeException.
    • The program is not going to compile if they aren’t dealt with.
    • Example: IOException, ClassNotFoundException, and so on.
  • Unchecked Exceptions
    • Those exceptions which might be checked at runtime includes unchecked exceptions.
    • They are youngster courses of RuntimeException.
    • They give runtime errors if not dealt with explicitly.
    • Example: ArithmeticException, NullPointerException and so on.

Difference between Checked and Unchecked Exception

Checked Exceptions Unchecked Exceptions
Occur at compile time. Occur at runtime.
The compiler checks for a checked exception. The compiler doesn’t verify for exceptions.
Can be dealt with on the compilation time. Can’t be caught or dealt with throughout compilation time.
The JVM requires that the exception be caught and dealt with. The JVM doesn’t require the exception to be caught and dealt with.
Example of Checked exception- ‘File Not Found Exception’ Example of Unchecked Exceptions- ‘No Such Element Exception’

Java Exception Index

Java Exception Keywords

Exception Handling in java is managed through 5 key phrases: attempt, catch, throw, throws, and eventually. Here are 5 key phrases which might be utilized in dealing with exceptions in Java

Keyword Description
attempt This key phrase is used to specify a block and this block should be adopted by both catch or lastly. That is, we are able to’t use attempt block alone.
catch This key phrase should be preceded by a attempt block to deal with the exception and might be adopted by a remaining block later.
lastly This key phrase is used to execute this system, whether or not an exception is dealt with or not.
throw This key phrase is used to throw an exception.
throws This key phrase is used to declare exceptions.

Java Try-Catch Block

Try-catch syntax:

attempt{
}
catch(Exception e){
}
public class ExceptionDemo {
	public static void principal (String[] args) {
		int a=10;
		for(int i=3;i>=0;i--)
		   attempt{
		     System.out.println(a/i);  
		   }catch(ArithmeticException e){
		       System.out.println(e);
		   }
	}
}

Output:

3
5
10
java.lang.ArithmeticException: / by zero 
  • attempt block incorporates the code that may throw an exception. Don’t write something further in attempt as statements after the exception is not going to get executed if the exception occurred. Try should be instantly adopted by catch or lastly block.
public class ExceptionDemo {
	public static void principal (String[] args) {
		int a=10;
		for(int i=3;i>=0;i--)
		   attempt{
		     System.out.println(a/i);  
		   }
	}
}

Compile-time error:

prog.java:5: error: 'attempt' with out 'catch', 'lastly' or useful resource declarations
    attempt{
    ^
1 error 
  • The catch block is used to catch the exception thrown by statements within the attempt block. The catch should comply with attempt else it would give a compile-time error.
public class ExceptionDemo {
	public static void principal (String[] args) {
		int a=10;
		for(int i=3;i>=0;i--)
		   attempt{
		     System.out.println(a/i);  
		   }
		   System.out.println("between attempt to catch");
		   catch(ArithmeticException e){
		       System.out.println(e);
		   }
	}
}

Compile Time Error:

prog.java:5: error: 'attempt' with out 'catch', 'lastly' or useful resource declarations
    attempt{
    ^
prog.java:9: error: 'catch' with out 'attempt'
    catch(ArithmeticException e){
    ^
2 errors 

Things to Remember:

Do not maintain any code after the assertion which is liable to exception. Because if an exception occurred, it would immediately bounce to the catch or lastly block, ignoring all different statements within the attempt block.

class Main {
	public static void principal (String[] args) {
         attempt
       {
             System.out.println(4/0);
	 //is not going to get printed
             System.out.println("finish of attempt!");
        }
catch(ArithmeticException e)
        {
            System.out.println("divide by 0");
        }
    }
}

Output:

divide by 0
  • While catching the exception within the catch block, both you’ll be able to have immediately the category of exception or its superclass.

Example: Exact Exception

class Main {
	public static void principal (String[] args) {
        attempt{
            System.out.println(4/0);
           }
      
        //ArithmeticException 
        catch(ArithmeticException e){
            System.out.println("divide by 0");
        }
    }
}

Output:

divide by 0

Example: Superclass of Exact Exception

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

Output:

divide by 0

Java Multiple Catch Block

If you’ve got a number of catches, it’s a must to preserve the hierarchy from subclass to superclass.

Incorrect:

class Main {
	public static void principal (String[] args) {
        attempt{
            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");
        }
	}
}

Compile-time error:

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

Correct:

class Main {
	public static void principal (String[] args) {
        attempt{
            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");
        }
   }
}

Output:

ArithmeticException: Divide by 0

Java Nested Try

When there’s one other attempt block inside the attempt block:

class Main {
	public static void principal (String[] args) {
        attempt{
                attempt{
                    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");
        }
	}
    }

Output:

Out of bounds
ArithmeticException: Divide by 0 

Note – If we put code of outer attempt earlier than inside attempt, then if an exception occurred, it would ignore all the inside attempt to transfer on to its catch block.

class Main {
	public static void principal (String[] args) {
        attempt{
               System.out.println(4/0);
               attempt{
                    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");
        }
	}
    }

Output:

ArithmeticException: Divide by 0

Java Finally Block

Contains code that should be executed regardless of if an exception is thrown or not. It incorporates code of file launch, closing connections, and so on.

class Main {
	public static void principal (String[] args) {
        attempt{
            System.out.println(4/0);
        }catch(Exception e)
        {
            System.out.println(e);       
        }
        lastly
        {
            System.out.println("lastly executed");
        }
        
       	        System.out.println("finish");
	}
}

Output:

java.lang.ArithmeticException: / by zero
lastly executed
finish 

Finally, will execute even when we don’t deal with exceptions. Before halting this system, JVM checks if there’s a “finally” block.

class Main {
	public static void principal (String[] args) {
        attempt{
            System.out.println(4/0);
            
        }lastly
        {
            System.out.println("cleansing.......");
        }
	}
}

Runtime Error:

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

Output:

cleansing.......

Java Final vs Finally vs Finalize

Final Finally Finalize
Final is used to use restrictions on class, methodology, and variable Finally is utilized in coding, it is going to be executed whether or not an exception is dealt with or not. Finalize is used to carry out clean-up processing earlier than rubbish is collected.
Final is a key phrase in java Finally is a block in java Finalize is a technique in java
Final is executed upon its name. Finally executes after”try-catch” block. finalize executes simply earlier than the destruction of the item.

Java Throw Keyword

It is a key phrase that’s used to explicitly throw an exception.

We can use throw the place in keeping with our logic an exception ought to happen.

Example:

public class ExceptionDemo {
	static void canVote(int age){
		if(age<18)
            attempt{
                throw new Exception();
            }catch(Exception e){
                System.out.println("you aren't an grownup!");
            }
		else
		   System.out.println("you'll be able to vote!");
	}
	public static void principal (String[] args) {
		canVote(20);
		canVote(10);
	}
}

Output:

you'll be able to vote!
you aren't an grownup! 

Java Throws Keyword

  • Throws key phrase is used when callee doesn’t wish to deal with the exception slightly it needs to increase this accountability of dealing with the exception to the caller of the operate.
  • Basically says what kind of exception the code can throw and depends on the caller to deal with it.
  • It is used to deal with checked Exceptions because the compiler is not going to enable code to compile till they’re dealt with.

Example:

public class ExceptionDemo {
	static void func(int a) throws Exception{
		   System.out.println(10/a);  
	}
	public static void principal (String[] args) {
		attempt{
		    func(10);
		    func(0);
		}catch(Exception e){
		   System.out.println("cannot divide by zero");
		}
	
	}
}

Output:

1
cannot divide by zero 

If callee can throw a number of exceptions, then all will probably be thrown concurrently.

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 principal (String[] args) {
		Scanner in=new Scanner(System.in);
		for(int i=0;i<3;i++){
		attempt{
		    func(in.nextInt(),in.nextInt());
    		}catch(ArithmeticException e){
    		   System.out.println("cannot divide by zero");
    		}catch(ArrayIndexOutOfBoundsException e){
    		   System.out.println("Out of bounds!");
    		}
		     }
		
	}
   }

Input:

2 1
0 1
2 3 

Output:

5
2
cannot divide by zero
5
Out of bounds! 

Java Throw vs Throws

Throw Throws
This key phrase is used to explicitly throw an exception. This key phrase is used to declare an exception.
A checked exception can’t be propagated with throw solely. A checked exception might be propagated with throws.
The throw is adopted by an occasion and used with a technique Throws are adopted by class and used with the tactic signature.
You can not throw a number of exceptions. You can declare a number of exceptions

Java Custom Exception

You can create your individual exception and provides implementation as to the way it ought to behave. Your exception will behave like a baby’s class of Exception.

Syntax:

 class YourException extends Exception{}
  • Example:
    • let’s say, you might be working with an airline firm 
    • You are within the baggage check-in division and as per guidelines, you’ll be able to enable 15kg per buyer.
    • So now greater than 15kg of weight is an irregular situation for us or in different phrases its an exception
    • This is our logic-based exception, so we’ll create our customized exception WeightLimitExceeded 
    • As per syntax, it would lengthen Exception.
    • We outline the constructor which is able to get invoked as quickly as an exception will probably be thrown
    • We should explicitly throw the exception and therefore we are going to use throw key phrase for that.
    • Using throws key phrase is as per our want. If we’re dealing with an exception the place it’s getting thrown then we are able to keep away from throws, else we are going to use throws and deal with it within the caller.

Implementation:

import java.util.*;

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


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

Input:

20
7 

Output:

5 kg : WeightLimitExceeded
You are able to fly! 

Exception Handling in java with methodology overriding

Exception Handling in Java with Method Overriding is an overridden methodology that declares to throw an exception and declare that it may well throw the identical exception or subtype of that exception.

To deal with the exception in Java, you’ll have to comply with three vital guidelines. They are depicted within the under determine.

exception handling in java
Exception Handling in Java with Method Overriding

Advantages and drawbacks of exception dealing with in java

Advantages of excepting dealing with in java 

  • Separating Error-Handling Code from “Regular” Code
  • Propagating Errors Up the Call Stack
  • Grouping and Differentiating Error Types

Disadvantages of excepting dealing with in java 

  • Experiencing pointless overhead
  • Not understanding how the appliance actually works
  • Filling your logs with noisy occasions
  • Inability to give attention to what truly issues

This brings us to the tip of this text on exception dealing with in java. We hope that you’re now clear concerning the idea of exception dealing with in java. If you want to know extra concerning the java programming language, then go surfing to our free java on-line course with certificates and energy forward in your profession.

Also Watch:

LEAVE A REPLY

Please enter your comment!
Please enter your name here