0% found this document useful (0 votes)
3 views71 pages

Exceptions

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views71 pages

Exceptions

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module "C#"

Submodule "C# Essentials"


Exception handling system

UA Resource Development Unit


CONFIDENTIAL
2020 1
AGENDA

1 Exception handling system

2 Exceptions. Exception arguments

3 Not handled exceptions


4 Exception raising stack

5 Operators try, catch, finally

6 Throwing exceptions

7 Exceptions in finally block

8 Custom exceptions

CONFIDENTIAL 2
Exception handling system

CONFIDENTIAL 3
Exception handling system: Why Handle Errors?

➢ Not crash program


➢ Chance to fix / retry
➢ Meaningful message & graceful exit
➢ Opportunity to log error

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

It is possible to handle an exception in a program


There is no way to handle an error using the program
using keywords such as try, catch, finally

Classified as an unchecked type Classified as checked and unchecked exceptions

Ex: OutOfMemoryError, StackOverFlowError and Ex: ArithmeticException, SQLException and


IOError NullPointerException
CONFIDENTIAL 5
Exception handling system: Errors

➢ Visual Studio IDE reports errors as soon as it can detect a problem

➢ Syntax error = compile errors:


▪ Language rule validation
▪ Easier to discover and eliminate

➢ C# adheres to set of rules known as C# Language Specifiction


▪ [Link]

CONFIDENTIAL 6
Exception handling system: Errors

CONFIDENTIAL 7
Exception handling system: Using Error Codes

private static int ProcessData()


{
// Process some data file
}
int errorCode = ProcessData();
if (errorCode == 0)
{
[Link]("Procrssed OK");
}
else if (errorCode == 1)
{
[Link]("ERROR: Invalid data");
}
else if (errorCode == 2)
{
[Link]("ERROR: Epmpty data file");
}
CONFIDENTIAL 8
Exception handling system: Using Error Codes

1. Need to know all the return values that represent error


2. Need to know all the return values that represent success
3. Need to remember to add an else if / switch statements for every return value
4. Program flow will continue as normal even though errors occurred and may
cause further damage
5. May be harder to read than exception handling code
6. Magic number with no semantic meaning harm readability / understanding

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?

➢ Don’t need to know all error / success codes


➢ Don’t need if / switch statements everywhere method is called
➢ More readable, less clutter
➢ No magic numbers / constants
➢ Exceptions can bubble up
➢ Catch exceptions higher up / in one place
➢ Handle system errors
➢ Generate exceptions from constructors

CONFIDENTIAL 12
Exceptions. Exception arguments

CONFIDENTIAL 13
What Is an Exception?

An exception is any error condition or unexpected behavior that is encountered by an


executing program. Exceptions can be thrown because of a fault in your code or in code
that you call (such as a shared library), unavailable operating system resources,
unexpected conditions that the runtime encounters (such as code that can't be verified),
and so on. Your application can recover from some of these conditions, but not from
others. Although you can recover from most application exceptions, you can't recover
from most runtime exceptions.

[Link]
CONFIDENTIAL 14
Reasons for exceptions: Code defects

int[] numbers = new[] { 2, 3, 5, 7 };


for (int i = 0; i <= [Link]; i++)
{
[Link](numbers[i]);
}
IndexOutOfRangeException

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

static void Main()


{ StackOverflowException
Main();
}

CONFIDENTIAL 16
Reasons for exceptions: Error conditions

static void PrintFile(string path)


{
foreach (string line in [Link](path))
{
[Link](line);
}
FileNotFoundException
}
if (![Link](path))
{
// Handle the problematic situation.
}

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

Standard exceptions Exceptions provided by


Custom application
provided by the .NET framework / library
exceptions
Framework authors

System Third party Custom

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

Exception Class Description

[Link] Handles I/O errors


[Link] Handles errors generated when a method refers to an array
index out of range.
[Link] Handles errors generated when type is mismatched with the
array type.
[Link] Handles errors generated from referencing a null object.

[Link] Handles errors generated from dividing a dividend with zero.

[Link] Handles errors generated during typecasting.

[Link] Handles errors generated from insufficient free memory.

[Link] Handles errors generated from stack overflow.


CONFIDENTIAL 23
Exception Class: Constructors

public Exception ();

public Exception (string message);

protected Exception ([Link] info,


[Link] context);

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

Try block Except


‘Statements ion

Catch block Yes


‘Statements

Finally block No
‘Statements

CONFIDENTIAL 27
Operators try, catch, finally

catch catch (type_exception)


{ {
// statements // statements
} }
try
{
int x = 5;
int y = x / 0;
[Link]($"Result: {y}");
}
catch(DivideByZeroException)
{
[Link]("Exception is DivideByZeroException");
}
CONFIDENTIAL 28
Operators try, catch, finally

catch (exception_type variable)


{
// statements
}

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);

public string GetFirstName()


{
var parts = [Link](" ");
return ([Link] > 0) ? parts[0] : throw new InvalidOperationException("No name!");
}

public string GetLastName() => throw new NotImplementedException();


}

CONFIDENTIAL 33
Operators try, catch, finally

The purpose of a try-catch block is to catch and


handle an exception generated by working
code. Some exceptions can be handled in a
catch block and the problem solved without
the exception being re-thrown; however, more
often the only thing that you can do is make
sure that the appropriate exception is thrown.

The purpose of a finally statement is to ensure


that the necessary cleanup of objects, usually
objects that are holding external resources,
occurs immediately, even if an exception is
thrown.

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.

Wrong Correct Only finally block

CONFIDENTIAL 35
Operators try, catch, finally

There are few possible ways to create catch block:

CONFIDENTIAL 36
Operators try, catch, finally

public async Task StartAnalyzingData()


{
try
{
// код
}
catch
{
await LogExceptionDetailsAsync();
}
finally
{
await CloseResourcesAsync();
}
}

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

throw [exception object];

FormatExeption ex = new FormatExeption("Argument has the wrong format");


throw ex;

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

▸ An inappropriate call to an object is


made, based on the object state.

▸ 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

The following list identifies practices to avoid when 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.

▸ Do not throw [Link], [Link], or


[Link] intentionally from your own source code.

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

public void DoBilling(int clientID)


{
Client client = _clientDataAccessObject.GetById(clientID);

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

▸ Use try/catch/finally blocks to handle exceptions

▸ Handle common conditions without throwing exceptions

▸ Throw exceptions instead of returning an error code

▸ Use the predefined .NET exception types

▸ End exception class names with the word Exception

▸ Use grammatically correct error messages

▸ Clean up intermediate results when throwing an exception

▸ In custom exceptions, provide additional properties as needed

CONFIDENTIAL 60
Guidelines and Best Practices Exception handling

Trading Reliability for Productivity

Possible exceptions:

▸ OutOfMemoryException

▸ TypeInitializationException

▸ OverflowException

▸ AppDomainUnloadedException

CONFIDENTIAL 61
Guidelines and Best Practices Exception handling

Use finally blocks liberally

CONFIDENTIAL 62
Guidelines and Best Practices Exception handling

Don’t catch everything

Wrong Correct

CONFIDENTIAL 63
Guidelines and Best Practices Exception handling

Recovering gracefully from an Exception

CONFIDENTIAL 64
Guidelines and Best Practices Exception handling

Backing out of a partially completed operation

CONFIDENTIAL 65
Guidelines and Best Practices Exception handling

Hiding an Implementation detail to maintain a “Contract”

CONFIDENTIAL 66
checked and unchecked

You can execute statements in C# in checked or unchecked context.

In checked, the exception is raised by arithmetic overflow, whereas in unchecked


context, arithmetic overflow is ignored.

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
}
}

public int Multiply(short operandX, short operandY)


{
return checked((short)(operandX * operandY));
}

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

I hope that you will find this material useful.

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]

With the note [.NET Online UA Training Course Feedback]

Thank you.

CONFIDENTIAL 71
Q&A

UA .NET Online LAB

CONFIDENTIAL
CONFIDENTIAL 72
3

You might also like