What are the different ways to handle exceptions?
#1) Using try/catch:
A 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:
1
class Manipulation{
2
public static void main(String[] args){
3
add();
4
}
5
Public void add(){
6
try{
7
addition();
8
}catch(Exception e){
9
e.printStacktrace();
10
}
11
}
12
}
#2) By declaring throws keyword:
At the end of the method, we can declare the exception using throws keyword.
Example:
view sourceprint?
1
class Manipulation{
2
public static void main(String[] args){
3
add();
4
}
5
public void add() throws Exception{
6
addition();
7
}
8
}