Exception Handling

While accessing websites, we sometimes come across weird messages like "500-Internal server error" or "404-page not found" on the screen that an end user cannot understand what these messages are. These are called exceptions. These exceptions occur when the technical team does not do good job in handling these exceptions.  Let us understand the overview on these exceptions (i.e. their meaning, interpretation) and how to handle them at high level in this post.


I. What is an exception? - An exception is an “unwanted or unexpected event”, which occurs during the execution of the program i.e, at run-time, that disrupts the normal flow of the program’s instructions. When an exception occurs, execution of the program gets terminated.

An exception can occur due to several reasons like Network connection problem, Bad input provided by user, Opening a non-existing file in your program etc.

Let us take an example application that helps you upload a file. When the user enters a file name on the web form and clicks upload button, below number of possible scenarios can occur that lead to exceptions.

1. The file might not exist on the client computer at all.
2. The file might already exists on the server computer.
3. The file might be too large to transfer over the internet.
4. The server might not have enough available disk space for the file.


Thus exceptions are unexpected behavior or error conditions. As developers, if we do not address these exceptions amicably, it attracts customer dissatisfaction. 

II. Error codes and their meaning.

Error code starts with Meaning
1xx (Informational): The request was received, continuing process
2xx (Successful): The request was successfully received, understood, and accepted
3xx (Redirection): Further action needs to be taken in order to complete the request
4xx (Client Error): The request contains bad syntax or cannot be fulfilled
5xx (Server Error): The server failed to fulfill an apparently valid request

III. Some of the frequently occurring error codes: Going with above standards, some of the most frequent errors that we come across are.

400 Bad Request - The server cannot or will not process the request due to an apparent client error (e.g., malformed request syntax, size too large, invalid request message framing, or deceptive request routing).
404 Not Found - The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.
500 Internal Server Error - A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
501 Not Implemented - The server either does not recognize the request method, or it lacks the ability to fulfil the request. Usually this implies future availability (e.g., a new feature of a web-service API).
502 Bad Gateway - The server was acting as a gateway or proxy and received an invalid response from the upstream server.
503 Service Unavailable - The server cannot handle the request (because it is overloaded or down for maintenance). Generally, this is a temporary state.
504 Gateway Timeout - The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.
505 HTTP Version Not Supported - The server does not support the HTTP protocol version used in the request.

IV. Blocks & Keywords used for exception handling.

1. try: The try block contains set of statements where an exception can occur.

try
{
   // statement(s) that might cause exception
}

(1) try block always contains problematic statements.
(2) If any exception is taking place, the control will be jumped automatically to appropriate "catch block".
(3) If any exception is taking place in try block, execution will be terminated and rest of the statements in try block will not be executed at all.

2. catch : Catch block is used to handle the uncertain condition of try block. A try block is always followed by a catch block, which handles the exception that occurs in associated try block.

catch
{
    // statement(s) that handle an exception
    // examples include closing a connection, closing file
    // exiting the process after writing details to a log file.
    // etc.
 }

(1) In catch block, we type the block of statements for providing user friendly messages by catching system error messages.
(2) catch block will be executed only if any exception error occurs in the try block.
(3) Even though, we write n number of catch blocks as part of exception handling program, only one catch block will be executed at any point based on the type of exception occurs.

3.finally: It is executed after catch block. We basically use it to put some common code when there are multiple catch blocks.

finally block
(1) finally block will be executed compulsory
(2) Writing the finally block is optional.
(3) finally block can contain statements that can release the resources that were used while opening files and opening databases etc.

4. throw: Throw keyword is used to transfer control from try block to catch block.

5. throws: Throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.


V. Example - Exception handling: Let us take an example to understand how to handle exceptions.

public class EHClass
{
   void ReadFile(int index)
   {
     // To run this code, substitute a valid path from your local machine
     string path = @"c:\users\public\test.txt";
     System.IO.StreamReader file = new System.IO.StreamReader(path);
     char[] buffer = new char[10];
     try
     {
     file.ReadBlock(buffer, index, buffer.Length);
     }
     catch (System.IO.IOException e)
     {
     Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
     }

     finally
     {
     if (file != null)
     {
     file.Close();
     }
     }
     // Do something with buffer...

   }

}