Upload
claire-ritchie
View
215
Download
1
Embed Size (px)
Citation preview
HANDLING EXCEPTIONS
(Using .NET Platform)
Note: Most of the material in these slides have been adapted from MSDN and wikipedia.
By Muhammad Ali
Error
?
Error
Types of ErrorsSyntacticalSemantic / LogicalRuntime
Why Exceptions ?
Many programmers do not test for all possible error conditionsReason ?
Trade Offs ?
Exceptions “Exceptions provide a clean way to
check for errors without cluttering code.”
How ?“Transfer control to treat a special case or
handle an error condition.”
Errors and Exceptions
Differences
Exception Handling “A programming language mechanism
designed to handle runtime errors or other problems
(exceptions)
inside a computer program.”
Behind the Scenes Exception Information Table (Per Executable).
Array of exception handling information (Per Method) in Exception Information Table.
Each entry of array describes a protected block of code, and any exception handlers.
Extremely Efficient StructureNo performance penalty in case an
exception doesn’t occur.
Exception Handling in C# Structured Exception Handling
Using try, catch, finally Blocks
Structured Exception Handling
tryCode that may cause an exception should be
placed in a ‘try block’
catchAfter the ‘try block’, usually one or more catch
blocks are written that respond to different exceptions, attempting to handle the exception
finallyCode that’ll execute no matter whether an
exception occurs or not
Spot Problematic Situations in this Innocent Looking Code
StreamReader streamReader = new StreamReader(fileName);
string fileContents = streamReader.ReadToEnd();
Console.WriteLine(fileContents);
streamReader.Close();
Console.WriteLine("\nThank you for using our software!\n");
Example try
{
StreamReader streamReader = new StreamReader(fileName);
string fileContents = streamReader.ReadToEnd();
Console.WriteLine(fileContents);
}
catch (FileNotFoundException fnfEx)
{
Console.WriteLine(fnfEx.Message);
Console.WriteLine(fnfEx.StackTrace);
} finally
{
if (streamReader != null)
{
streamReader.Close();
}
}
Multiple Catch Blocks try
{
StreamReader streamReader = new StreamReader(fileName);
string fileContents = streamReader.ReadToEnd();
Console.WriteLine(fileContents);
}
catch (FileNotFoundException fnfEx)
{
Console.WriteLine(fnfEx.Message);
Console.WriteLine(fnfEx.StackTrace);
} catch (IOException ioEx)
{
Console.WriteLine(ioEx.Message);
Console.WriteLine(ioEx.StackTrace);
}
finally
{
if (streamReader != null)
{
streamReader.Close();
}
}
Derived
Base
Tackling ‘Unknown’ Cases try
{
StreamReader streamReader = new StreamReader(fileName);
string fileContents = streamReader.ReadToEnd();
Console.WriteLine(fileContents);
}
catch (FileNotFoundException fnfEx)
{
Console.WriteLine(fnfEx.Message);
Console.WriteLine(fnfEx.StackTrace);
} catch (IOException ioEx)
{
Console.WriteLine(ioEx.Message);
Console.WriteLine(ioEx.StackTrace);
} catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
finally
{
if (streamReader != null)
{
streamReader.Close();
}
}
Some Useful Properties HelpLink
Gets or sets the location of the help file associated with the exception
Message Gets the string representation of the error message
associated with the exception
Source Gets or sets the name of the application or object that
caused the exception
StackTrace Gets the stack trace identifying the location in the code
where the exception occurred
Different Shapes of (try-catch-finally)
A try block followed by one or more catch blocks
A try block followed by one finally block (No catch
block)
A try block followed by one or more catch blocks and a
finally block
Image Source: http://book.javanb.com/From-Java-To-Csharp-A-Developers-Guide/FILES/13fig04.gif
Standard Exceptions
Two types of Exceptions
Exceptions generated by an executing program
Exceptions generated by CLR.
Standard Exceptions The common language runtime throws
System Exception.
Excpetion thrown by a user program is called Application Exception.
The System Exception includes the ExecutionEngineException StackOverFlowExceptionetc.
Application Exception
System.NullReferenceException
Syste.InvalidCastException
Syste.ArrayTypeMismatchException
System.IndexOutOfRangeException
System.OverFlowException
Throwing an Exception Explicitly The ‘throw’ keyword.
General form
throw exception_obj;
Throwing an Exception Explicitly Following statement throws an
Exception explicitly.
throw new Exception(“Exception Message");
…Ctd
It is NOT recommended that we catch System Exceptions that we cannot handle nor is it good programming practice to throw System Exceptions that we cannot handle in our applications
User Defined Exceptions
In C#, it is possible to create our own exception class.
How?
Exception must be the ultimate base class for all exceptions in C#.
So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes
Design Guidelines Exceptions should be used to communicate
exceptional conditions.
Don’t use them to communicate events that are expected, such as reaching the end of a file.
If there’s a good predefined exception in the System namespace use that.
If code catches an exception that it isn’t going to handle, Consider whether it should wrap that exception with
additional information before re-throwing it.