Chapter 11 - Exception Handling

15
Exception Handling 1 C# 30 C# 3.0 C# 3.0 Chapter 11 – Exception Handling © Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel Exception Handling Introduction Exception Handling 2 C# 30 Exception Handling Introduction NET uses exception handling to report .NET uses exception handling to report errors Makes ignoring errors significantly harder! Facilitates separation of error-handling and happy- flow Provides more detailed error information A standard cross-language convention of error reporting (unlike HRESULTS, enum codes etc.) Available for any method independent of its signature (constructors, operators, properties…) © Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

description

o

Transcript of Chapter 11 - Exception Handling

Page 1: Chapter 11 - Exception Handling

Exception Handling 1C# 30

C# 3.0C# 3.0

Chapter 11 – Exception Handling

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Exception Handling IntroductionException Handling 2C# 30

Exception Handling Introduction

• NET uses exception handling to report• .NET uses exception handling to report errors– Makes ignoring errors significantly harder!– Facilitates separation of error-handling and happy-

flow– Provides more detailed error information– A standard cross-language convention of error

reporting (unlike HRESULTS, enum codes etc.)– Available for any method independent of its signature

(constructors, operators, properties…)

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 2: Chapter 11 - Exception Handling

Exception Handling IntroductionException Handling 3C# 30

Exception Handling Introduction

E ception handling in a n tshell• Exception handling in a nutshell:– Exceptions are used to report an anomalous condition

– When an exception object a search for an appropriate error handler starts

– If an appropriate error handler block is found, it is executedexecuted

– If no appropriate error handler is found, the program is terminatedis terminated

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Exception Handling SyntaxException Handling 4C# 30

Exception Handling Syntax

The thro statement is used to throw• The throw statement is used to throw exceptionsp

• The try and catch blocks are used to handle exceptionshandle exceptions

• The finally block executes regardless of whether an exception was thrownwhether an exception was thrown– More on this later

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 3: Chapter 11 - Exception Handling

NET ExceptionsException Handling 5C# 30

.NET Exceptions

FCL classes se e ceptions to report• FCL classes use exceptions to report errors:– .NET defines a set of exception types to be thrown by

FCL classes and user codeFCL classes and user code

– .NET method documentation includes the exceptions that might be thrown by this methodthat might be thrown by this method

• Note: unlike Java, this is not binding!

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Handling ExceptionsException Handling 6C# 30

Handling Exceptions

• The application requires a file name from• The application requires a file name from the user and processes the file providedp p

• In its first version, the application completely ignores exceptionscompletely ignores exceptions

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 4: Chapter 11 - Exception Handling

Exception HandlingException Handling 7C# 30

Ignoring Exceptionsiusing System;

using System.IO;

class FileApp {static void Main() {

while (true) {while (true) {Console.WriteLine ("Enter file name:");string fName = Console.ReadLine();

StreamReader file = File.OpenText(fName);Console.WriteLine(“Processing {0}...", file.Name);

// Process the specified fileConsole.WriteLine(“Processed {0}", file.Name);file.Close();

}}

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

}}

Exception HandlingException Handling 8C# 30

Ignoring Exceptions

In the happ flo e er thing orks• In the happy flow, everything works

• If the user enters a bad file name, theIf the user enters a bad file name, the program is terminated:

Enter file name: NonExistent.txt

Unhandled Exception: System.IO.FileNotFoundException:p y pCould not find file 'd:\Temp\NonExistent.txt'.File name: 'd:\Temp\NonExistent.txt'

at System.IO.__Error.WinIOError...at System.IO.FileStream.Init...at System.IO.FileStream..ctor...at System.IO.FileStream..ctor...at System.IO.StreamReader..ctor...at System.IO.StreamReader..ctor...at System.IO.File.OpenText(String path)t Fil A M i ()

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

at FileApp.Main()

Page 5: Chapter 11 - Exception Handling

Handling ExceptionsException Handling 9C# 30

Catching and Displaying Exceptions• “Risky” code blocks are enclosed within a• Risky code blocks are enclosed within a try block,

• Followed by one or more catch blocks• Followed by one or more catch blocks– One for each exception type

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Handling ExceptionsException Handling 10C# 30

Catching and Displaying Exceptionsi i i () {static void Main() {

while (true) {try {y {

StreamReader file = File.OpenText(fName);// Process the specified fileConsole.WriteLine(“Processing {0}... “,Console.WriteLine( Processing {0}...  ,

file.Name.);Console.WriteLine(“Processed {0}", 

file Name);file.Name);file.Close();

}t h (Fil N tF dE ti ) {catch (FileNotFoundException) {

Console.WriteLine(“File was not found");Console.WriteLine(“Check file & try again");

}}

}

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

}

Page 6: Chapter 11 - Exception Handling

Catching ExceptionsException Handling 11C# 30

Catching Exceptions

We’ e identified an e ception sing its• We’ve identified an exception using its typeyp

• But an exception object contains more information that just its typeinformation that just its type

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The NET Exception ClassException Handling 12C# 30

The .NET Exception Class

NET e ceptions are deri ed from• .NET exceptions are derived from System.Exceptiony p– Contains properties that provide information about the

source and cause of the exceptionsource and cause of the exception

Message the exception information– Message – the exception information

– StackTrace – the trace of methods that led to the tiexception source

– InnerException – wrapped exception object

– HResult – a numeric error code that represents the exception (if applicable)

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 7: Chapter 11 - Exception Handling

Displaying an ExceptionException Handling 13C# 30

Displaying an Exception

E ception ToString() renders the• Exception.ToString() renders the exception as a stringp g– Includes the message, source, stack trace and inner

exception (recursively if applicable)exception (recursively if applicable)

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Catching NotesException Handling 14C# 30

Catching Notes

Deciding at hich inheritance le el to• Deciding at which inheritance level to catch exceptions is importantp p– Don’t catch anything overly general – you can’t really

handle it!handle it!

• catch block order is important:Specific blocks before general blocks– Specific blocks before general blocks

– Try to avoid catch-all

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 8: Chapter 11 - Exception Handling

(Some) System Exception TypesException Handling 15C# 30

(Some) System Exception TypesException Type Thrown whenException Type Thrown when…

OutOfMemoryException An attempt to allocate memory (via new) fails.

StackOverflowException The execution stack is exhausted from too many pending method calls (e.g., unlimited recursion)unlimited recursion).

NullReferenceException A null reference is inappropriately used.

InvalidCastException An explicit cast of a base type or anInvalidCastException An explicit cast of a base type or an interface to a derived type fails at run time.

IndexOutOfRangeException An attempt to index an array with an index that is less than zero or out of bounds.

ArithmeticException A base class for arithmetic operationsArithmeticException A base class for arithmetic operations exceptions (e.g. DivideByZeroException)

ArgumentException An invalid argument was provided to a

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

g p g pmethod.

Throwing ExceptionsException Handling 16C# 30

Throwing Exceptions

• Exceptions are thrown using the syntax:• Exceptions are thrown using the syntax:

throw [exception];

– When rethrowing from a catch block, the exception

throw [exception];

When rethrowing from a catch block, the exception itself is implied

• But … Which exception should be thrown?– We can throw an exception of an existing exceptionWe can throw an exception of an existing exception

type, or of a new user-defined one

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 9: Chapter 11 - Exception Handling

Throwing ExceptionsException Handling 17C# 30

A Pre-Defined Exceptionbli  E l  thi  [i t i d ] {  // i d  d l tipublic Employee this [int index] {  // indexer declaration

get {{

if (index < 0 || index >= _numEmployees)throw new IndexOutOfRangeException();

lelsereturn _employees[index];

}}set {

if (i d  < 0 || i d  >   E l )if (index < 0 || index >= _numEmployees)throw new IndexOutOfRangeException();

elseemployees[index] = value;

}}

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

}

Throwing ExceptionsException Handling 18C# 30

Customizing Pre-Defined ExceptionsS stem E ception has several• System.Exception has several constructors:– Parameterless

– With a message string (initializes the Message– With a message string (initializes the Messageproperty)

With a message string and an exception to wrap– With a message string and an exception to wrap (initializes the Message and InnerExceptionproperties)properties)

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 10: Chapter 11 - Exception Handling

Throwing ExceptionsException Handling 19C# 30

Customizing Pre-Defined Exceptions

public EmployeesManager(int maxEmployees){{if (maxEmployees <= 0){{

throw new ArgumentException("Illegal maxEmployees number provided: “ +

E lmaxEmployees +"maxEmployees should be > 0");

}}

_employees = new Employee[maxEmployees];}}

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Wrapping ExceptionsException Handling 20C# 30

Wrapping Exceptions

• Use inner exceptions when a call• Use inner exceptions when a call propagates several layers down in the

li tiapplication– E.g. client-to-server Remoting callg g– E.g. UI calls into BL that calls into DAL

• Wrap an exception only if you have information to addinformation to add

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 11: Chapter 11 - Exception Handling

User-Defined ExceptionsException Handling 21C# 30

User-Defined Exceptions

• Create a user defined exception class if• Create a user-defined exception class if you have a new category of errors– That is not represented by any framework exception– E.g., don’t write a MyCollectionOutOfRangeException (you’ve got IndexOutOfRangeException working for you)B t d it– But do write a MyCollectionLoadFactorExceededException

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

User-Defined ExceptionsException Handling 22C# 30

Guidelines• A user defined exception type name• A user-defined exception type name

should:– Have its name suffixied with Exception– Derive from System.Exception (directly or indirectly)– Have the three standard constructors (and call the

base versions from them)

• The easiest way to create an exception• The easiest way to create an exception type is to use the Visual Studio “exception”

i tsnippet

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 12: Chapter 11 - Exception Handling

User-Defined ExceptionsException Handling 23C# 30

Sampleclass BadFileFormatException : Exception {class BadFileFormatException : Exception {public BadFileFormatException() : base () {  }public BadFileFormatException(

string fileName, string problem): base ("The file: “ + fileName +

"has a format error: "+ problem) {has a format error:  + problem) {this.fileName = fileName;

}public BadFileFormatException(

string fileName, string problem, Exception inner): base ("The file: “ + fileName +: base ( The file:   + fileName +

"has a format error: "+ problem, inner) {this.fileName = fileName;

}private string fileName;public string FileName { get { return fileName; } }

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

public string FileName { get { return fileName; } }}

Resource ManagementException Handling 24C# 30

Resource Management

• Handling resources that must be released• Handling resources that must be released is difficult with exception handling:– There might be several exit points to the method– Any couple of lines might throw an exception

• How did we handle such a situation inHow did we handle such a situation in C++?

C th t h i h ?– Can we use the same technique here?– Do you have any other ideas?

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 13: Chapter 11 - Exception Handling

The finally StatementException Handling 25C# 30

The finally Statement

• In C++ we could do cleanup in the• In C++ we could do cleanup in the destructor– But C# finalizers are non-deterministic

• The answer is a finally block– Placed after a try block or a try catch block it is– Placed after a try block or a try…catch block, it is

guaranteed to execute regardless of whether an exception was thrownp

• Disposable resources benefit from the• Disposable resources benefit from the using keyword as well

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Resource ManagementException Handling 26C# 30

finally Blockstatic void ProcessFile(string fName)static void ProcessFile(string fName){

FileStream file = File.Open(fName, FileMode.Open);try{

ProcessBasic(file);ProcessBasic(file);ProcessAdvanced(file);

}finally{{

file.Close();}

}

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 14: Chapter 11 - Exception Handling

Checked and Unchecked Exception Handling 27C# 30

Arithmetic• The O erflo E ception is thrown in• The OverflowException is thrown in

case of an overflow due to an arithmetic or conversion operation

The checked and unchecked keywords are used to– The checked and unchecked keywords are used to create contexts in which overflow will either be checked or not be checkedchecked or not be checked

– There are special IL instructions for checked operationsoperations

• Overflow check can be enforced also by ythe compiler flag /checked

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Design GuidelinesException Handling 28C# 30

Design Guidelines

• Use exceptions for exceptional conditions• Use exceptions for exceptional conditions only

• Do not use return values to report errors• Throw pre defined exceptions if• Throw pre-defined exceptions, if

appropriate• Create your own exception type if dealing

with a new category of errorswith a new category of errors• Consider wrapping an original exception

l if h dditi l t t lonly if you have additional contextual information

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 15: Chapter 11 - Exception Handling

Exception Handling 29C# 30

Chapter 11 Exercise 1

IMPLEMENTING EXCEPTION HANDLINGHANDLING

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Chapter SummaryException Handling 30C# 30

Chapter Summary

In NET & C# e se e ceptions to report• In .NET & C# we use exceptions to report an error

• Exception is an error handling h i th t t b i dmechanisms that can not be ignored

• You can throw a predefined systemYou can throw a predefined system exception or you can create your own

• block

The finally keyword is used to handle non• The finally keyword is used to handle non-memory resources in case of exception

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

y p