Professional Documents
Culture Documents
Exceptions
and
Object Lifetime
1 School of CSE
Content
• What is an Exception? – basics
• System.Exception Class
• Catching an Exception
• System Level Exceptions
• Building Customized Exceptions
• Multiple Exceptions
• Garbage Collection - basics
• What is "finally"?
• Building Finallizable and Disposable Types
2 School of CSE
Introduction
An exception is any error condition or unexpected
behavior encountered by an executing program. These
are run time anomalies.
In the .NET Framework, an exception is an object that
inherits from the
System.Exception class
An exception is thrown from an area of code where a
problem has occurred
.NET base class libraries define:
OutOfMemoryException, IndexOutOfRangeException,
FileNotFoundException, and so on
3 School of CSE
.NET Exceptions
4 School of CSE
.NET Exceptions …
• The CLR supports an exception handling model based
on the concepts of exception objects and protected
blocks of code
• The runtime creates an object to represent an exception
when it occurs. You can also create your own exception
classes by deriving classes from the appropriate base
exception
• Each language uses a form of try/catch/finally structured
exception handling
5 School of CSE
Why Exceptions?
Code that uses exceptions are clearer and more robust
than other methods
bool RemoveFromAccount(string AcctID, decimal Amount)
{
bool Exists = VerifyAmount(AcctID);
if (Exists)
{
bool CanWithDraw = CheckAv(AcctID, Amount);
if (CanWithDraw)
{ return WithDraw(AcctID, Amount); }
}
return false;
}
6 School of CSE
Disadvantages of
Traditional Methods
7 School of CSE
Handling Exceptions
To handle an exception you must protect with a
try block and have at least one catch block
try
{
Employee e;
e.GiveBonus(); // null reference
}
catch
{
// Handle any exception
}
8 School of CSE
How Exceptions are Executed?
• To catch an exception the try-catch block must be used
• A try block is a section of the code that looks for an
exception
• When an exception is raised, or thrown, within a try
block, an exception object is created and a search begins
in the catch block
• When an exception occurs within that scope, the control
goes to the appropriate catch block (handler)
• If no exception occurs, obviously the catch block is never
executed
• After the catch block code is executed the rest of the
code in the program continues (is it OK?)
• Catch block can also rethrow the exception
9 School of CSE
try Catching Specific Exceptions
{
Employee e;
e.GiveBonus(); // null reference
}
catch (NullReferenceException ex)
{
// Log the error
throw(ex);
}
If the catch block can recover from the error that caused the
exception, execution can continue after catch block. If it can't,
then it must rethrow (shown in red color).
If an exception is rethrown, the next catch block will be
checked. The check may continue in the call stack until a proper
handler is found. If none found, terminate!
10 School of CSE
throw statement
The throw statement is used to signal the occurrence of
an anomalous situation /exception and to send the error
object back to the caller (raising an exception)
throw [expression];
expression is an exception object
Usually the throw statement is used with try-catch or try-
finally statements. When an exception is thrown, the
program looks for the catch statement that handles this
exception
11 School of CSE
Example (throw)
using System;
public class ThrowTest
{
public static void Main()
{
Output:
string s = null; The following exception occurs:
if (s == null) System.ArgumentNullException
{
throw(new ArgumentNullException());
}
// not executed
Console.Write("The string s is null");
}
}
12 School of CSE
Example (try - catch)
using System;
class AddInts
{
static void Main(string[] args)
{
int a, b;
int c, d = 0;
Console.Write("Enter the first number (a): ");
a = System.Int32.Parse(Console.ReadLine());
Console.Write("Enter the second number (b): ");
b = System.Int32.Parse(Console.ReadLine());
c = a + b;
13 School of CSE
try
{
d = a / b;
}
catch(Exception e)
{
Console.WriteLine("Method: {0}", e.TargetSite);
Console.WriteLine("Message: {0}", e.Message);
Console.WriteLine("Source: {0}", e.Source);
return;
}
Console.WriteLine("a + b = {0}", c);
Console.WriteLine("a / b = {0}", d);
}
}
Enter the first number (a): 28
Enter the second number (b): 0
Method: Void Main(System.String[]) //which method threw the exception
Message: Attempted to divide by zero.
14 School of
Source: CSE
AddInts
System.Exception Base Class
Most of the memebers defined by System.Exception
are read-only
Property Meaning
HelpLink URL to a help file
InnerException details of previous exceptions that
caused the current exception
Message returns the text describing the error
Source name of the assembly that threw the
exception
StackTrace sequence of calls that triggered the
exception
TargetSite returns the MethodBase type
15 School of CSE
Example-2 : StackTrace
StackTrace: Displays sequence of calls that
resulted in throwing the exception. We can
follow the flow of the error's origin
catch(Exception e)
{
Console.WriteLine("Stack: {0}",e.StackTrace);
}
16 School of CSE
Example-3 : HelpLink
try
{
// create a new Exception object, passing a string
Exception myException = new Exception("myException");
// set the HelpLink and Source properties
myException.HelpLink = "See the Readme.txt file";
myException.Source = "My HelpLink Program";
// throw the Exception object
throw myException;
}
catch (Exception e)
{
// display the exception object's properties
Console.WriteLine("HelpLink = " + e.HelpLink);
Console.WriteLine("Source = " + e.Source);
}
HelpLink = See the Readme.txt file
17 School of CSE Source = My HelpLink
Building Custom Exceptions
18 School of CSE
Square Root
using System;
namespace CustomException
{
class NegNumException : ApplicationException
{
class NegNumException : ApplicationException
{
public NegNumException()
: base("SNG: Negative Number Exception")
{}
public NegNumException(string msg)
: base(msg)
{}
public NegNumException(string msg, Exception inner)
: base(msg, inner)
{}
}
19 School of CSE
Square Root…
class CustomException
{
public double SqRoot(double n)
{
if (n < 0)
// calls 1-arg ctor.
// throw new NegNumException
("SNG: Negative Number not allowed");
// calls default ctor.
throw new NegNumException();
return Math.Sqrt(n);
}
20 School of CSE
Square Root…
public void SqRootTest()
{
double n;
try
{
Console.Write("Enter a number: ");
n = System.Double.Parse(Console.ReadLine());
double result = SqRoot(n);
Console.WriteLine("Sq Root = {0}", result);
}
catch(FormatException ex)
{
Console.WriteLine(ex.Message);
}
catch(NegNumException ex)
{
Console.WriteLine(ex.Message);
}
}
21 School of CSE
Square Root…
static void Main(string[] args)
{
CustomException e = new CustomException();
e.SqRootTest();
}
}
}
22 School of CSE
Multiple Exceptions
• The code in the try block may trigger more than
one exception.
• Under these circumstances you can have more
than one catch block
• Exception will be processed by the nearest
available catch block (Below example is wrong!)
• Ex: try { … }
catch (Exception e) {…}
catch (NegNumException e) {…}
catch (ArgumentOutOfRangeException e) {…}
Unreachable
23 School of CSE
Other types of Exception Handling
Generic catch
try {…} No argument
catch
{…}
Rethrowing Exceptions
try {…}
catch (NegNumException e)
{
// handle the error and pass the buck
throw e;
} rethrow the same
exception
The finally Block
- The optional finally block will get executed always
- Useful for cleaning up process or close the database files
24 School of CSE
Garbage Collection
C# Programmers never directly deallocate an object from memory –
so no 'delete' keyword
Rule: Allocate an object on to a managed heap using 'new' and forget
about it!
How does .NET determine that an object is no longer needed? When it
is unreachable by the current application
Example:
public static int Main(string[] args)
{
Car c = new Car( );
…. When the application
} shuts down, object c
may be destroyed.
25 School of CSE
Garbage Collector
c3 c2 c1 Unused heap
next object pointer
26 School of CSE
Garbage Collector…
• If the managed heap does not have enough memory, CLR
does garbage collection. It frees the memory to accommodate
the new object
• Which object memory is to be removed – "no longer needed"
basis
• Objects that have been recently allocated are most likely to
be freed
• Objects that have lived the longest are least likely to be
become free
• Objects allocated together will be used together
• To get this idea CLR uses an object graph to know whether
the objects are still in use.
• The other objects which are no longer used – "severed roots"
or unreachable objects are reclaimed and the memory is
compacted with necessary object pointer adjustment
27 School of CSE
Garbage Collector…
28 School of CSE