Exceptions
Exceptions
6 Throwing exceptions
8 Custom exceptions
CONFIDENTIAL 2
Exception handling system
CONFIDENTIAL 3
Exception handling system: Why Handle Errors?
CONFIDENTIAL 4
Exception handling system: Error VS Exception
ERROR EXCEPTION
An indication of an unexpected condition that occurs An issue in a program that prevent the normal flow of
due to lack of system resource the program
Occurred due to the lack of system resource Occurred due to an issue in the program
Irrecoverable Recoverable
CONFIDENTIAL 6
Exception handling system: Errors
CONFIDENTIAL 7
Exception handling system: Using Error Codes
CONFIDENTIAL 9
Exception handling system: Using Error Codes
private static int ProcessData()
{
// Process some data file
}
int errorCode = ProcessData();
if (errorCode == OK)
0)
{
[Link]("Procrssed OK");
}
else if (errorCode == DATA_ERROR)
1)
{
[Link]("ERROR: Invalid data");
}
else if (errorCode == EMPTY_FILE)
2)
{
[Link]("ERROR: Empty data file");
}
CONFIDENTIAL 10
Exception handling system: Using Error Codes
1. Need to add if / switch statements every time method is called to check return codes
2. Errors do not “bubble up” the call stack
3. Catch some errors at a higher level
4. Catch some error in a single place
5. How do you deal with system errors?
▪ Out of memory
▪ Access violations
6. How do you return an error from a constructor?
CONFIDENTIAL 11
Why Exceptions?
CONFIDENTIAL 12
Exceptions. Exception arguments
CONFIDENTIAL 13
What Is an Exception?
[Link]
CONFIDENTIAL 14
Reasons for exceptions: Code defects
FormatException
[Link]("What’s your age ?");
string age = [Link]();
int yearOfBirth = [Link] - [Link](age);
[Link]($"I bet you were born around {yearOfBirth}.");
CONFIDENTIAL 15
Reasons for exceptions: Runtime disasters
CONFIDENTIAL 16
Reasons for exceptions: Error conditions
CONFIDENTIAL 17
Catching Exceptions in C#
In .NET, an exception is an
object that inherits from
the [Link] class.
An exception is thrown
from an area of code
where a problem has
occurred. The exception is
passed up the stack until
the application handles it
or the program
terminates.
CONFIDENTIAL 18
Exception Definitions
CONFIDENTIAL 19
FCL - Defined Exception classes
CONFIDENTIAL 20
The [Link] class: Properties
Name Description
Data Gets a collection of key/value pairs that provide additional user-defined
information about the exception.
HelpLink Gets or sets a link to the help file associated with this exception.
HResult Gets or sets HRESULT, a coded numerical value that is assigned to a specific
exception.
InnerException Gets the Exception instance that caused the current exception.
Message Gets a message that describes the current exception.
Source Gets or sets the name of the application or the object that causes the error.
StackTrace Gets a string representation of the immediate frames on the call stack.
TargetSite Gets the method that throws the current exception.
CONFIDENTIAL 21
The [Link] class: Methods
Name Description
Equals(Object) Determines whether the specified object is equal to the current object.
(Inherited from Object)
Finalize() Allows an object to try to free resources and perform other cleanup operations
before it is reclaimed by garbage collection. (Inherited from Object).
GetBaseException() When overridden in a derived class, returns the Exception that is the root cause
of one or more subsequent exceptions.
GetHashCode() Serves as the default hash function. (Inherited from Object)
GetObjectData(SerializationInfo, When overridden in a derived class, sets the SerializationInfo with information
StreamingContext) about the exception.
GetType() Gets the runtime type of the current instance.
MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object.)
ToString() Creates and returns a string representation of the current exception. (Overrides
[Link]())
CONFIDENTIAL 22
Exceptions. Exception Class
CONFIDENTIAL 24
Operators try, catch, finally
CONFIDENTIAL 25
Control flow of Exceptions
try
{
[Try block.]
}
catch ([catch specification 1])
{
[Catch block 1.]
}
...
catch ([catch specification n])
{
[Catch block n.]
}
CONFIDENTIAL 26
Control flow of Exceptions
Finally block No
‘Statements
CONFIDENTIAL 27
Operators try, catch, finally
try
{
int x = 5;
int y = x / 0;
[Link]($"Result: {y}");
}
catch(DivideByZeroException ex)
{
[Link]($"Exception is {[Link]}");
}
CONFIDENTIAL 29
Operators try, catch, finally
catch when(condition)
{
//Statements
}
CONFIDENTIAL 30
Exception Filters
WebClient wc = null;
try {
wc = new WebClient(); //downloading a web page
var resultData = [Link]("[Link]
}
catch (WebException ex) when ([Link] == [Link])
{
//code specifically for a WebException ProtocolError
}
catch (WebException ex) when (([Link] as HttpWebResponse)?.StatusCode == [Link])
{
//code specifically for a WebException NotFound
}
catch (WebException ex) when (([Link] as HttpWebResponse)?.StatusCode == [Link])
{
//code specifically for a WebException InternalServerError
}
finally {
//call this if exception occurs or not
wc?.Dispose();
}
CONFIDENTIAL 31
Exception Filters
class Person
{
public string Name { get; }
public Person(string name) => Name = name ?? throw new ArgumentNullException(name);
CONFIDENTIAL 33
Operators try, catch, finally
CONFIDENTIAL 34
Operators try, catch, finally
There can be multiple catch blocks, but only the one that first matches the exception type is
executed. That means you need to order the catch blocks properly.
CONFIDENTIAL 35
Operators try, catch, finally
CONFIDENTIAL 36
Operators try, catch, finally
CONFIDENTIAL 37
Exceptions in finally block
CONFIDENTIAL 38
Exceptions in finally block
try
{
[Try block.]
}
catch ([catch specification 1])
{
[Catch block 1.]
}
...
catch ([catch specification n])
{
[Catch block n.]
}
finally
{
[Finally block.]
}
CONFIDENTIAL 39
Exceptions in finally block
try
{
OpenFile("MyFile"); // Open a file
WriteToFile(...); // Write some data to the file
}
catch (IOException ex)
{
[Link]([Link]);
}
finally
{
CloseFile("MyFile"); // Close the file
}
CONFIDENTIAL 40
Exception raising stack
CONFIDENTIAL 41
Exception raising stack
CONFIDENTIAL 42
Exception raising stack
try
{
// Try block.
}
catch
{
// Catch block.
} try
{
// Try block.
}
catch (Exception ex)
{
// Catch block, can access exception in ex.
}
CONFIDENTIAL 43
Exception raising stack
try
{
// Try block.
}
catch (DivideByZeroException ex)
{
// Catch block, can access
// DivideByZeroException exception in ex.
}
catch (Exception ex)
{
// Catch block, can access exception in ex.
}
CONFIDENTIAL 44
Exception raising stack
try
{
// Outer try block.
...
try
{
// Nested try block
}
catch (FileNotFoundException ex)
{
// Catch block for nested try block
}
...
// Outer try block continued
}
catch (DivideByZeroException ex)
{
// Catch block, can access DivideByZeroException exception in ex.
}
catch (Exception ex)
{
// Catch block, can access exception in ex.
}
CONFIDENTIAL 45
Throwing exceptions
CONFIDENTIAL 46
Throwing exceptions
CONFIDENTIAL 47
Throwing exceptions
Once an exception is thrown, it propagates up the call stack until a catch statement for the
exception is found.
CONFIDENTIAL 48
Throwing exceptions
Exceptions are used to indicate that an error has occurred while running the program.
Exception objects that describe an error are created and then thrown with the throw
keyword. The runtime then searches for the most compatible exception handler.
Programmers should throw exceptions when one or more of the following conditions are
true:
▸ The method cannot complete its defined functionality.
CONFIDENTIAL 49
Throwing exceptions
▸ When an argument
to a method causes
an exception.
CONFIDENTIAL 50
Throwing exceptions
try
{
try
{
[Link]("Input Line: ");
string message = [Link]();
if ([Link] > 6)
{
throw new Exception("Line length greater than 6 characters");
}
}
catch
{
[Link]("Exception!");
throw;
}
}
catch (Exception ex)
{
[Link]([Link]);
}
CONFIDENTIAL 51
Throwing exceptions
▸ Exceptions should not be used to change the flow of a program as part of ordinary execution.
Exceptions should only be used to report and handle error conditions.
▸ Exceptions should not be returned as a return value or parameter instead of being thrown.
CONFIDENTIAL 52
Throwing exceptions: Standard exception classes
When you have to throw an exception, you can often use an existing exception type in the
.NET Framework instead of implementing a custom exception.
Exception Condition
ArgumentException A non-null argument that is passed to a method is invalid.
ArgumentNullException An argument that is passed to a method is null.
ArgumentOutOfRangeException An argument is outside the range of valid values.
DirectoryNotFoundException Part of a directory path is not valid.
DivideByZeroException The denominator in an integer or [Link] division operation is zero.
FileNotFoundException A file does not exist.
IndexOutOfRangeException An index is outside the bounds of an array or collection.
NotImplementedException A method or operation is not implemented.
OverflowException An arithmetic, casting, or conversion operation results in an overflow.
CONFIDENTIAL 53
Not handled exceptions
CONFIDENTIAL 54
Not handled exceptions
CONFIDENTIAL 55
Custom exceptions
CONFIDENTIAL 56
Custom exceptions
if (client == null)
{
throw new ClientBillingException([Link]("Unable to find a client by id {0}", clientID));
}
}
public class ClientBillingException : Exception
{
public ClientBillingException(string message) : base(message)
{
}
}
CONFIDENTIAL 57
Custom exceptions
Programs can throw a predefined exception class in the System namespace or create their
own exception classes by deriving from Exception. The derived classes should define at
least four constructors: one default constructor, one that sets the message property, and
one that sets both the Message and InnerException properties. The fourth constructor is
used to serialize the exception. New exception classes should be serializable.
CONFIDENTIAL 58
Guidelines and Best
Practices Exception handling
CONFIDENTIAL 59
Guidelines and Best Practices Exception handling
CONFIDENTIAL 60
Guidelines and Best Practices Exception handling
Possible exceptions:
▸ OutOfMemoryException
▸ TypeInitializationException
▸ OverflowException
▸ AppDomainUnloadedException
CONFIDENTIAL 61
Guidelines and Best Practices Exception handling
CONFIDENTIAL 62
Guidelines and Best Practices Exception handling
Wrong Correct
CONFIDENTIAL 63
Guidelines and Best Practices Exception handling
CONFIDENTIAL 64
Guidelines and Best Practices Exception handling
CONFIDENTIAL 65
Guidelines and Best Practices Exception handling
CONFIDENTIAL 66
checked and unchecked
Checked Exceptions
Use the checked keyword to explicitly enable overflow checking for integral-type
arithmetic operations and conversions. For this, just set the checked keyword.
Unchecked Exception
Use the unchecked keyword to prevent overflow checking for integral-type
arithmetic operations and conversions. For this, just set the unchecked keyword.
CONFIDENTIAL 67
checked
checked
{
int x = ...;
int y = ...;
int z = ...;
try
{
z = x * y; // May cause numeric overflow
}
catch (OverflowException ex)
{
... // Handle the overflow exception
}
}
CONFIDENTIAL 68
unchecked
unchecked
{
int1 = 2147483647 + 10;
}
...
int1 = unchecked(ConstantMax + 10);
CONFIDENTIAL 69
unchecked
unchecked
{
int1 = 2147483647 + 10;
}
...
int1 = unchecked(ConstantMax + 10);
CONFIDENTIAL 70
.NET Online UA Training Course Feedback
If you find errors or inaccuracies in this material or know how to improve it, please report
on to the electronic address:
Oleksii_Leunenko@[Link]
Thank you.
CONFIDENTIAL 71
Q&A
CONFIDENTIAL
CONFIDENTIAL 72
3