In this article we will learn about exception handling in C#. Exceptions are errors that can occur during the program execution. If we do not provide any way to handle exceptions then, by default the program execution is terminated and detailed asp.net exceptions are displayed to the user. We use the Try, Catch, Finally block for exceptional handling.
Try block
Here we write the code that has to be watched for exceptions.
Catch Block
Here we write the code that tells what action has to be done when an exception occurs. Common actions include logging the exception in database or application log or we can display the details of exceptions.
We can have zero, one or more catch blocks.
Zero Catch blocks
//try, finally
try
{
//statements
}
finally
{
//statements
}
One catch block
//try, catch
try
{
//statements
}
catch (SomeException ex)
{
//statements
}
//try, catch and finally
try
{
//statements
}
catch (SomeException ex)
{
//statements
}
finally
{
//statements
}
Multiple catch blocks
//try, multiple catch,finally
try
{
//statements
}
catch (OracleException ex)
{
//statements
}
catch (Exception ex)
{
//statements
}
finally
{
//statements
}
In case of multiple catch blocks, more specialized catch block should come before a generalized one.
//try, multiple catch,finally
try
{
//statements
}
catch (OracleException ex)
{
//statements
}
catch (Exception ex)
{
//statements
}
finally
{
//statements
}
To catch all exceptions use catch block without a bracket or arguments.
try
{
//statements
}
catch
{
}
Finally Block
Here we write the code that is executed always, irrespective of whether exception occurs or not. We generally free up the resources here. This is optional block.
Example using Try, Catch, Finally block
string ConnectionString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
OleDbConnection conn = null;
OleDbDataReader sdr = null;
string OdbcName = "";
try
{
conn = new OleDbConnection(ConnectionString);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "StoredProc1";
cmd.Parameters.AddWithValue("@param1", "value1");
cmd.Parameters.AddWithValue("@param2", "value2");
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
OdbcName = sdr[0].ToString();
}
sdr.Close();
}
catch(OleDbException se)
{
HttpContext.Current.Response.Redirect("~/AutoError.aspx?errorCode="+se.ErrorCode+"&details=" + se.Message.ToString());
}
finally
{
if (sdr != null)
sdr.Close();
if (conn != null)
conn.Close();
}
throw
We can explicitly throw an exception using the throw clause.
eg:-
try
{
//some statements
throw new DivideByZeroException(“Exception thrown by me”);
}
catch(DivideByZeroException e)
{
//some processing
}
We can rethrow the exception also.
eg:-
try
{
//some statements
throw new DivideByZeroException(“Exception thrown by me”);
}
catch(DivideByZeroException e)
{
throw e;//rethrowing
//or
throw//rethrowing
}
System.Exception is the base class for all exceptions.
All pre-defined common language runtime exception classes are derived from SystemException class. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions.
Common SystemExceptions are
System.OutOfMemoryException
System.NullReferenceException etc.
All user-defined application exception classes are derived from ApplicationException class.
Example of creating a user defined exception
public class UserDefinedException : ApplicationException
{
public UserDefinedException()
{
}
public UserDefinedException(string message)
:base(message)
{
}
}
Using that exception
try
{
throw new UserDefinedException("My exception");
}
catch(UserDefinedException ex)
{
Response.Output.WriteLine(ex.Message);
}
0 Comments Received
Post a Comment