What are the different ways to handle exceptions and what are the advantages of Exception handling?


There are two different ways to handle exceptions are explained below:

a) Using try/catch:

The risky code is surrounded by try block. If an exception occurs, then it is caught by the catch block which is followed by the try block.

Example:

class Manipulation{
public static void main(String[] args){
add();
}
Public void add(){
try{
addition();
}catch(Exception e){
e.printStacktrace();
}
}
}

b) By declaring throws keyword:

At the end of the method, we can declare the exception using throws keyword.

Example:

class Manipulation{
public static void main(String[] args){
add();
}
public void add() throws Exception{
addition();
}
}

The advantages are as follows:

  • The normal flow of the execution won’t be terminated if an exception gets handled
  • We can identify the problem by using catch declaration

Post a Comment

0 Comments