There are several ways to handle the expections. Below is the explanation with their examples and you can try it on your own as well.
The try block indicates a possible exceptions in results.
The on block indicates a possibly handling of exceptions when the exceptions type are specified. The catch block occurs when it catches an exceptions on try block.
The finally block is used when the handle does not specifies an handling of exception objects irrespective of an exception’s occurence. Finally block executes unconditionally after try/on/catch block.
Syntax
try{
//statements that throw an expections
}
on Exception1{
//statements that throw an expections on specified exceptions
}
catch Exception2{
// statements for handling exception
}
finally{
//statements for handlinng exception
}
The code can have more catch blocks for multiple exceptions handling. The try block is associated with both the other blocks (catch and finally) so both the blocks are mutually inclusive.
Example using ON block
void main(){
int num = 5;
int i=0;
int result ;
try{
result = num/i;
}
on IntegerDivisionByZeroException{
print("Cannot divide by zero");
}
}
output
Cannot divide by zero
The code throws an exception since it is trying to divide by zero which is not possible.
Example using catch block
void main(){
int num = 5;
int i=0;
int result ;
try{
result = num/i;
}
catch(e){
print("e");
}
}
output
IntegerDivisionByZeroException
We can also use on..catch in the same line of code and use it like below.
Example of on..catch block
void main(){
int num = 5;
int i=0;
int result ;
try{
result = num/i;
}
on IntegerDivisionByZeroException catch(e){
print("e");
}
}
It produces the following output:-
IntegerDivisionByZeroException
void main(){
int num = 5;
int i=0;
int result ;
try{
result = num/i;
}
on IntegerDivisionByZeroException catch(e){
print("e");
finally{
print("Finally block is executed irrespective of exception's occurence")
}
}
}
It produces the following output:-
IntegerDivisionByZeroException
Finally block is executed irrespective of exception's occurence