In this article, you will learn exception handling using try-catch-finally block. In later part, you will learn using nested catch block and use of throw keyword.
You can perform exception handling using try-catch-finally blocks, nested catch block and throw keyword. This article explains all these one by one.
There are three ways you can implement try-catch-finally blocks into your program.
We mostly use try-catch and try-catch-finally blocks in our program.
try{
//Code here
} catch {
//code here
} finally {
//code here
}
This block contains main business logic and error mainly encounter in this block only. You write inline code, call functions or do other stuffs in this block only.
Whenever a program encounter any exception, it is caught in catch block. You can catch exception in catch block, specify base Exception class to show type of error or specifically mention particular exception type to catch specific error like "DivideByZeroException".
This block execute in every case i.e. after execution of try block or even if encounter an error caught in catch block. We write those logic in finally block which we want to execute regardless of any condition.
You can implement nested try-catch-finally block and can catch inner error under nested catch block.
try{
//Code here
try{
//Code here
} catch {
//code here
} finally {
//code here
}
} catch {
//code here
} finally {
//code here
}
This keyword is used to catch and throw inner exception to parent catch block. This is helpful when you want to collect all errors at one place i.e. parent catch block and handle all error at one go. This is mostly used keyword in Exception Handling.
try{
//Code here
} catch {
//code here
throw;
} finally {
//code here
}
In catch block, either you can simply throw error to parent block or handle in same catch block or you can customize exception like showing exception message or see stack trace using pre-defined exception class "Exception" or you can specifically use specific class like "DivideByZeroException", "NullReferenceException", "IndexOutOfRangeException" and many more.
try{
//Code here
} catch (Exception ex){
//code here
throw ex;
}finally {
//code here
}
You can also multiple catch blocks to handle exceptions separately. In below example, we used multiple catch blocks. Note that you should use "Exception" class at last if you are using multiple catch blocks.
try{
//Code here
} catch (OutOfMemoryException ex){
//code here
throw ex;
} catch (Exception ex){
//code here
throw ex;
}finally {
//code here
}
Hope this helps you.