Exception Handling
Exception Handling
Agha Azeem
[email protected]
Table of Contents
1. What are Exceptions?
2. Handling Exceptions
3. The System.Exception Class
4. Types of Exceptions and their
Hierarchy
5. Raising (Throwing) Exceptions
6. Best Practices
2
What are Exceptions?
The Paradigm of Exceptions in OOP
What are Exceptions?
The exceptions in .NET Framework are classic
implementation of the OOP exception model
Deliver powerful mechanism for centralized
handling of errors and unusual events
Substitute procedure-oriented approach,
in which each function returns error code
Simplify code construction and maintenance
4
Handling Exceptions
Catching and Processing Errors
Handling Exceptions
In C# the exceptions can be handled by the
try-catch-finally construction
try
{
// Do some work that can raise an exception
}
catch (SomeException)
{
// Handle the caught exception
}
6
Handling Exceptions – Example
static void Main()
{
string s = Console.ReadLine();
try
{
Int32.Parse(s);
Console.WriteLine(
"You entered valid Int32 number {0}.", s);
}
catch (FormatException)
{
Console.WriteLine("Invalid integer number!");
}
catch (OverflowException)
{
Console.WriteLine(
"The number is too big to fit in Int32!");
}
}
7
Handling
Exceptions
Live Demo
The System.Exception Class
Exceptions in .NET are objects
The System.Exception class is base for all
exceptions in CLR
Contains information for the cause of the error /
unusual situation
Message – text description of the exception
StackTrace – the snapshot of the stack at the
moment of exception throwing
InnerException – exception caused the current
exception (if any)
9
Exception Properties – Example
class ExceptionsExample
{
public static void CauseFormatException()
{
string s = "an invalid number";
Int32.Parse(s);
}
static void Main()
{
try
{
CauseFormatException();
}
catch (FormatException fe)
{
Console.Error.WriteLine("Exception: {0}\n{1}",
fe.Message, fe.StackTrace);
}
}
}
10
Exception Properties
The Message property gives brief description of the
problem
The StackTrace property is extremely useful when
identifying the reason caused the exception
11
Exception Properties (2)
File names and line numbers are accessible only if the
compilation was in Debug mode
When compiled in Release mode, the information in
the property StackTrace is quite different:
12
Exception Properties
Live Demo
The Hierarchy of
Exceptions
Exception Hierarchy
Exceptions in .NET Framework are organized
in a hierarchy
System.Exception
System.SystemException System.ApplicationException
System.NullReferenceException System.FormatException
System.ArithmeticException SofiaUniversity.InvalidStudentException
System.DivideByZeroException System.OverflowException
15
Types of Exceptions
.NET exceptions inherit from System.Exception
The system exceptions inherit from
System.SystemException, e.g.
System.ArgumentException
System.NullReferenceException
System.OutOfMemoryException
System.StackOverflowException
User-defined exceptions should inherit from
System.ApplicationException
16
Handling Exceptions
When catching an exception of a particular class,
all its inheritors (child exceptions) are caught too
Example:
try
{
// Do some works that can cause an exception
}
catch (System.ArithmeticException)
{
// Handle the caught arithmetic exception
}
19
Throwing Exceptions
Throwing Exceptions
Exceptions are thrown (raised) by throw
keyword in C#
Used to notify the calling code in case of
error or unusual situation
When an exception is thrown:
Method N Method N
… 4. Method call … 6. Find handler
Method 2 Method 2
3. Method call 7. Find handler
Method 1 Method 1
2. Method call 8. Find handler
Main() Main()
.NET
CLR
22
Using throw Keyword
Throwing an exception with an error message:
throw new ArgumentException("Invalid amount!");
Exceptions can accept message and cause:
try
{
Int32.Parse(str);
}
catch (FormatException fe)
{
throw new ArgumentException("Invalid number", fe);
}
Note: if the original exception is not passed the
initial cause of the exception is lost
23
Re-Throwing Exceptions
Caught exceptions can be re-thrown again:
try
{
Int32.Parse(str);
}
catch (FormatException fe)
{
Console.WriteLine("Parse failed!");
throw fe; // Re-throw the caught exception
}
catch (FormatException)
{
throw; // Re-throws the last caught exception
}
24
Throwing Exceptions – Example
public static double Sqrt(double value)
{
if (value < 0)
throw new System.ArgumentOutOfRangeException(
"Sqrt for negative numbers is undefined!");
return Math.Sqrt(value);
}
static void Main()
{
try
{
Sqrt(-1);
}
catch (ArgumentOutOfRangeException ex)
{
Console.Error.WriteLine("Error: " + ex.Message);
throw;
}
}
25
Throwing Exceptions
Live Demo
Choosing the Exception Type
When an invalid parameter is passed to a method:
ArgumentException, ArgumentNullException,
ArgumentOutOfRangeException
When requested operation is not supported
NotSupportedException
When a method is still not implemented
NotImplementedException
If no suitable standard exception class is available
Create own exception class (inherit Exception)
27
Using Try-Finally Blocks
The try-finally Statement
The statement:
try
{
// Do some work that can cause an exception
}
finally
{
// This block will always execute
}
http://academy.telerik.com 37
Exercises
1. Write a program that reads an integer number and
calculates and prints its square root. If the number is
invalid or negative, print "Invalid number". In all
cases finally print "Good bye". Use try-catch-finally.
2. Write a method ReadNumber(int start, int end)
that enters an integer number in given range
[start…end]. If an invalid number or non-number text
is entered, the method should throw an exception.
Using this method write a program that enters 10
numbers:
a1, a2, … a10, such that 1 < a1 < … < a10 < 100
38
Exercises (2)
3. Write a program that enters file name along with its
full file path (e.g. C:\WINDOWS\win.ini), reads its
contents and prints it on the console. Find in MSDN
how to use System.IO.File.ReadAllText(…). Be
sure to catch all possible exceptions and print user-
friendly error messages.
4. Write a program that downloads a file from Internet
(e.g. http://www.devbg.org/img/Logo-BASD.jpg) and
stores it the current directory. Find in Google how to
download files in C#. Be sure to catch all exceptions
and to free any used resources in the finally block.
39
Free Trainings @ Telerik Academy
Fundamentals of C# Programming
Course
csharpfundamentals.telerik.com
Telerik Software Academy
academy.telerik.com
Telerik Academy @ Facebook
facebook.com/TelerikAcademy
Telerik Software Academy Forums
forums.academy.telerik.com