Definition :
"An exception is an error condition or unexpected behavior encountered by an executing application during runtime."
Exceptions can occur in programs due to various reasons including bad logic, non-availability of operating system resources, network failure, attempt to access invalid objects etc. When the code which has a problem is executed, it 'raises an exception'.
For example, if network connection to the database server is broken when you are accessing some data, .Net Framework will raise an exception. Or, if you are attempting to read a File which do not exist, .Net framework will raise a 'File Not Found' exception.
When an exception is raised in the system, if it is not 'handled', it will lead to program termination. This will give a bad experience for the user and may lead to loss or corruption of data.
.Net framework provides very good, structured exception handling mechanism. In .Net, an 'exception' is a class, which is derived from System.Exception class. When there is a problem ('exception') in the code, .net runtime creates an 'exception' object which contains information about the nature of the problem. If you handle the exception in the code, you will receive this exception object which contains information about the nature of the error. This information can be used to show a friendly message to the user or to recover from the error and continue executing the program.
How to Handle Exceptions in C#
Exceptions are handled in .Net using the 'try/catch/finally' statements. The code which 'may cause an exception' is enclosed within a 'try' block as shown below:
try { // some code that may cause an exception. }
Now we are safe. You have protected your code. If an exception occurs in the code enclosed within the 'try' block, you can handle it. To handle an exception, attach a 'catch' block to the 'try'.
try { // some code that may cause an exception. // If an exception occurs in the above code, the execution will not continue within the // 'try' block. Instead, the execution will jump to the 'catch' block. } catch (Exception ex) { // If an exception occurs in the try block, this block will be executed. // Write the error handling code here. }
When an exception is raised, the control of execution is transfered to the 'catch' block. You can write the error handling code here. Yo may show a friendly message to the user or try to recover from the error by writing appropriate code.
In the above case, we are blindly catching all exceptions. You may change the 'catch' block slightly to handle only specific types of exceptions.
In the following example, we are attempting to copy a file to a new name. If the file doesn't exists, it will throw a 'FileNotFound' exception.
try { System.IO.File.Copy ( "C:\\test.txt", "C:\\new.txt" ); } catch ( System.IO.FileNotFoundException ex ) { MessageBox.Show( ex.Message ); }
In this case, if 'c:\test.txt' doesn't exists, then it will throw an exception. We are catching this specific type of exception in the 'catch' block and displaying the 'exception message' to the user.
NOTE: It is not a good idea to display the raw exception message to the user. Instead, show a friendly message to the user and log the actual exception message to some log file for trouble shooting purposes.
In the above example, we are handling only a specific type of exception : 'System.IO.FileNotFoundException'. If any other type fo exception occurs in the above code, it is not handled and will lead to program termination. For example, if an exception of type 'OutOfMemoryException' occurs, it is not handled and program will terminate.
To catch all types of exceptions, specify the root 'Exception' in the 'catch' block. But it is a bad practise to catch all exceptions. You should catch only specific exceptions which are expected in teh specific code block. For example, if you are accessing a file, you may catch 'System.IO.FileNotFoundException' and if you are performing mathemtical operations, you may catch 'System.DivideByZeroException' exception. Also, you can create and throw custom exceptions. If the code you are calling is expected to throw any custom exception, you may catch those custom exceptions.
Handling more than one Exception
You can have zero or more 'catch' blocks attached with each 'try' blocks. Depending on the type of the exception thrown, appropriate 'catch' block will be executed.
try { // some code that can throw exception. } catch ( System.IO.FileNotFoundException ex ) { MessageBox.Show( ex.Message ); } catch ( System.DivideByZeroException ex ) { MessageBox.Show( ex.Message ); }
The above code sample handles two specific exception types : FileNotFoundException & DivideByZeroException. When an exception occurs within the 'try' block, it will first check wether it is of type 'FileNotFoundException'. If so, it executes that catch block. If not, it will check whether it is of type 'DivideByZeroException'. If the exception doesn't belong to one of these types, it will not be handled.
A root exception matches all exceptions derived from it. Since all exceptions are derived from System.Exception, if you catch 'System.Exception', it will catch all exceptions.
try { // some code that can throw exception. } catch ( System.Exception ex ) { MessageBox.Show( ex.Message ); } catch ( System.IO.FileNotFoundException ex ) { MessageBox.Show( ex.Message ); } catch ( System.DivideByZeroException ex ) { MessageBox.Show( ex.Message ); }
In the above code, 'catch ( System.Exception ex )' will catch all exceptions including 'FileNotFoundException' and 'DivideByZeroException'. So even if the 'DivideByZeroException' occurs, it will be handled by the first catch block. So, if you handle more than one exception, the inherited ones should be handled first. If catching 'System.Exception', it should be the last 'catch' block.
Using the 'finally' statement to perform cleanup operations
try { // some code that can throw exception. } catch ( System.Exception ex ) { MessageBox.Show( ex.Message ); } finally { MessageBox.Show( "exiting the try/catch block" ); }
The 'finally' block is guaranteed to be executed whether there is an exception or not. If there is NO exception raised within the 'try' block, the 'finally' block is executed after executing the last statement within the try block.
If an exception is raised within the 'try' block, then 'catch' block is executed. After executing the last statementin the 'catch' block, the 'finally' block is executed.
The purpose of the 'finally' block is to provide a way to perform any cleanup operations. For example, if you are opening a file and performing some file operations within the 'try' block, you can do the file closing within the 'finally' block. This will ensure that the file is closed even if there is an exception during file operations.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|