Exception Dealing with in Java with Examples

Connect With Us


exception handling in java

Exception dealing with in java is among the highly effective mechanisms to deal with runtime errors attributable to exceptions. Exception dealing with performs an vital position in software program improvement. This text helps you perceive java exception, exception in java, java exception dealing with, java exception hierarchy, forms of exception in java, and lots of extra.

What’s Exception Dealing with in Java?

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

Additionally Learn: Java Tutorial for rookies

What’s an Exception?

An expectation is an surprising occasion that happens whereas executing this system, that disturbs the conventional movement 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

exception handling in java

1. JVM

If an exception will not be dealt with explicitly, then JVM takes the duty of dealing with the exception.

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

import java.util.*;

class Most important {
    public static void major (String[] args) {
        System.out.println(5/0);
        System.out.println("Finish of program!");
	}
}

Runtime Error:

 Exception in thread "major" java.lang.ArithmeticException: / by zero
 at Most important.major(File.java:5) 

2. Developer

Builders can explicitly write the implementation for dealing with the exception. As soon as an exception is dealt with, the conventional 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 Dealing with in Java dealing with hierarchy.

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

Varieties of exception in Java

  • Checked Exceptions
    • These exceptions which are checked at compile-time contains checked exceptions.
    • They’re youngster lessons of Exception apart from RuntimeException.
    • This system is not going to compile if they aren’t dealt with.
    • Instance: IOException, ClassNotFoundException, and so on.
  • Unchecked Exceptions
    • These exceptions which are checked at runtime contains unchecked exceptions.
    • They’re youngster lessons of RuntimeException.
    • They offer runtime errors if not dealt with explicitly.
    • Instance: ArithmeticException, NullPointerException and so on.

Distinction between Checked and Unchecked Exception

Checked Exceptions Unchecked Exceptions
Happen at compile time. Happen at runtime.
The compiler checks for a checked exception. The compiler doesn’t test for exceptions.
Could 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.
Instance of Checked exception- ‘File Not Discovered Exception’ Instance of Unchecked Exceptions- ‘No Such Aspect Exception’

Java Exception Index

Java Exception Key phrases

Exception Dealing with in java is managed by way of 5 key phrases: strive, catch, throw, throws, and at last. Listed here are 5 key phrases which are utilized in dealing with exceptions in Java

Key phrase Description
strive This key phrase is used to specify a block and this block should be adopted by both catch or lastly. That’s, we are able to’t use strive block alone.
catch This key phrase should be preceded by a strive block to deal with the exception and will be adopted by a last 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 Strive-Catch Block

Strive-catch syntax:

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

Output:

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

Compile-time error:

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

Compile Time Error:

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

Issues to Bear in mind:

Don’t maintain any code after the assertion which is susceptible to exception. As a result of if an exception occurred, it would immediately soar to the catch or lastly block, ignoring all different statements within the strive block.

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

Output:

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

Instance: Precise Exception

class Most important {
	public static void major (String[] args) {
        strive{
            System.out.println(4/0);
           }
      
        //ArithmeticException 
        catch(ArithmeticException e){
            System.out.println("divide by 0");
        }
    }
}

Output:

divide by 0

Instance: Superclass of Precise Exception

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

Output:

divide by 0

Java A number of Catch Block

You probably have a number of catches, it’s important to preserve the hierarchy from subclass to superclass.

Incorrect:

class Most important {
	public static void major (String[] args) {
        strive{
            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 

Appropriate:

class Most important {
	public static void major (String[] args) {
        strive{
            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 Strive

When there may be one other strive block inside the strive block:

class Most important {
	public static void major (String[] args) {
        strive{
                strive{
                    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 

Word – If we put code of outer strive earlier than internal strive, then if an exception occurred, it would ignore the whole internal try to transfer on to its catch block.

class Most important {
	public static void major (String[] args) {
        strive{
               System.out.println(4/0);
               strive{
                    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 Lastly Block

Comprises code that should be executed irrespective of if an exception is thrown or not. It accommodates code of file launch, closing connections, and so on.

exception handling in java
class Most important {
	public static void major (String[] args) {
        strive{
            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 

Lastly, will execute even when we don’t deal with exceptions. Earlier than halting this system, JVM checks if there’s a “lastly” block.

class Most important {
	public static void major (String[] args) {
        strive{
            System.out.println(4/0);
            
        }lastly
        {
            System.out.println("cleansing.......");
        }
	}
}

Runtime Error:

 Exception in thread "major" java.lang.ArithmeticException: / by zero
 at Most important.major(File.java:4) 

Output:

cleansing.......

Java Last vs Lastly vs Finalize

Last Lastly Finalize
Last is used to use restrictions on class, technique, and variable Lastly is utilized in coding, it will likely 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.
Last is a key phrase in java Lastly is a block in java Finalize is a technique in java
Last is executed upon its name. Lastly executes after”try-catch” block. finalize executes simply earlier than the destruction of the article.

Java Throw Key phrase

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

We will use throw the place based on our logic an exception ought to happen.

Instance:

public class ExceptionDemo {
	static void canVote(int age){
		if(age<18)
            strive{
                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 major (String[] args) {
		canVote(20);
		canVote(10);
	}
}

Output:

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

Java Throws Key phrase

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

Instance:

public class ExceptionDemo {
	static void func(int a) throws Exception{
		   System.out.println(10/a);  
	}
	public static void major (String[] args) {
		strive{
		    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 might 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 major (String[] args) {
		Scanner in=new Scanner(System.in);
		for(int i=0;i<3;i++){
		strive{
		    func(in.nextInt(),in.nextInt());
    		}catch(ArithmeticException e){
    		   System.out.println("cannot divide by zero");
    		}catch(ArrayIndexOutOfBoundsException e){
    		   System.out.println("Out of bounds!");
    		}
		     }
		
	}
   }

Enter:

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 will 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’t throw a number of exceptions. You may declare a number of exceptions

Java Customized Exception

You may create your personal 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{}
  • Instance:
    • let’s say, you might be working with an airline firm 
    • You might be 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
    • That is our logic-based exception, so we’ll create our customized exception WeightLimitExceeded 
    • As per syntax, it would prolong Exception.
    • We outline the constructor which is able to get invoked as quickly as an exception might be thrown
    • We’ve to explicitly throw the exception and therefore we’ll use throw key phrase for that.
    • Utilizing 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’ll 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 Most important {
    void validWeight(int weight) throws WeightLimitExceeded{
        if(weight>15)
            throw new WeightLimitExceeded(weight);
        else
            System.out.println("You might be able to fly!");
    }
    
      public static void major (String[] args) {
        Most important ob=new Most important();
        Scanner in=new Scanner(System.in);
        for(int i=0;i<2;i++){
            strive{
                ob.validWeight(in.nextInt());
            }catch(WeightLimitExceeded e){
                System.out.println(e);
            }
        }
        
	}
}

Enter:

20
7 

Output:

5 kg : WeightLimitExceeded
You might be able to fly! 

Exception Dealing with in java with technique overriding

Exception Dealing with in Java with Technique Overriding is an overridden technique that declares to throw an exception and declare that it might probably throw the identical exception or subtype of that exception.

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

exception handling in java
Exception Dealing with in Java with Technique Overriding

Benefits and drawbacks of exception dealing with in java

Benefits of excepting dealing with in java 

  • Separating Error-Dealing with Code from “Common” Code
  • Propagating Errors Up the Name Stack
  • Grouping and Differentiating Error Varieties

Disadvantages of excepting dealing with in java 

  • Experiencing pointless overhead
  • Not understanding how the applying actually works
  • Filling your logs with noisy occasions
  • Incapability to deal with what really issues

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

Additionally Watch:

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

Translate »