Top Banner
Exceptions
23

Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

Dec 21, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

Exceptions

Page 2: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

2

Objectives

• Introduce C# exception handling– library exception types– custom exceptions

• Describe keywords used for exception handling– try– catch– throw– finally

Page 3: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

3

Exception pattern

• Exceptions are a notification mechanism• Pattern:

– exception generated when condition detected– propagated back through the call chain– caught and handled at higher level

One() Two() Three() Divide()Main()

call sequence

problem occurs in Divide,search for error handlerunwinds call sequence

Page 4: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

4

Predefined exceptions

• .NET Framework defines many exception types– for common conditions– implemented as library classes– names end in Exception

class ArithmeticException ... { ... }

class FileNotFoundException ... { ... }

class IndexOutOfRangeException ... { ... }

class InvalidCastException ... { ... }

class NullReferenceException ... { ... }

class OutOfMemoryException ... { ... }

Page 5: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

5

Exception types

• Exceptions organized into inheritance hierarchy– all derived from Exception– system exceptions from SystemException– user defined exceptions from ApplicationException

ApplicationExceptionSystemException

Exception

Page 6: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

6

Exception generation

• Exception generated with keyword throw– must create and throw exception object– can generated by user code, CLR, or .NET Framework

int[] data;...data[index] = 17;CLR

FileStream f = new FileStream("MyFile.dat", FileMode.Open);Framework

int Divide(int n, int d){ if (d == 0) throw new DivideByZeroException("divide by zero");

return n / d;}

user code

Page 7: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

7

Catching exceptions

• User code can handle exception– regular code placed in try block– handler code put inside catch clause

void Process(){ try { int[] data = new int[10];

data[10] = 17; ... } catch (IndexOutOfRangeException e) { ... }}

error

execute handler

code skipped

Page 8: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

8

Multiple catch

• A try block can have multiple catch clauses– tested in order– only matching handler executed

void Process(int index){ try { int[] data = new int[10]; data[index] = 17; ... } catch (OutOfMemoryException e) { ... } catch (IndexOutOfRangeException e) { ... }}

handle failure of new

handle invalid index

Page 9: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

9

Locating a handler

• Appropriate handler chosen by type thrown– unwind stack until caught– non-matching handlers ignored– thread terminates if exception not caught

void One(){ try { Two(); } catch (DivideByZeroException e) { ... }}

void Two(){ try { Three(); } catch (IOException e) { ... }}

void Three(){ int q;

q = Divide(3, 0);

...}

will be executed

throws exception

Page 10: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

10

Exception objects

• Exception objects contain information about error– Message and StackTrace defined in Exception class– available in all exception types– specific exception types may add more information

void Process(){ try { ... } catch (IndexOutOfRangeException e) { string msg = e.Message;

string trace = e.StackTrace; }}

access exception info

Page 11: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

11

Catching base class

• Can catch base class– also catches all derived class

void Process(){ try { ... } catch (IOException e) { ... }}

catch IOExceptionand all derived classes

FileNotFoundException

IOException

EndOfStreamException

Page 12: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

12

Catch clause ordering

• Most specific catch must be listed first– derived class before base– otherwise base clause would catch all– derived clause would never be reached

void Process(){ try { ... } catch (FileNotFoundException e) { ... } catch (IOException e) { ... }}

derived

FileNotFoundException

IOException

base

Page 13: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

13

Catching Exception

• Catching Exception catches all derived types of Exception– base class for all exception types

void Process(){ try { ... } catch (Exception e) { ... } ...}

catch anyexception

Page 14: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

14

General catch clause

• catch clause without specification catches all exceptions– called general catch clause

void Process(){ try { ... } catch { ... } ...}

catch anyexception

Page 15: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

15

Throw without argument

• throw with no argument re-throws current exception– useful when combined with general catch

void Process(){ try { ... } catch { ...

throw; } ...}

catch any exception

do local cleanup

propagate exception

Page 16: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

16

Resource release

• Difficult to release resources in presence of exceptions– exception may cause cleanup code to be skipped

void Process(){ FileStream data = new FileStream("File.dat", FileMode.Create); data.WriteByte(0x10);

...

data.Close();}

skipped whenexception thrown

may throwexception

Page 17: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

17

Finally

• try can have optional finally block– always executed when control leaves associated try block– catch block(s) allowed but not required– useful for cleaning up resources

void Process(){ FileStream data = null;

try { data = new FileStream("File.dat", FileMode.Create); data.WriteByte(0x10); ... } finally { data.Close(); }}

always executed

Page 18: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

18

Custom exception

• Can create custom exception types– should derive from ApplicationException– should choose name ending in Exception

BadAccountException

Exception

ApplicationException

Page 19: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

19

Implementing custom exception

• Custom exception typically:– stores addition data describing error– provides constructor that takes string error message– chains to base constructor to store string

class BadAccountException : ApplicationException{ public int id;

public BadAccountException(string msg, int id) :base(msg) { this.id = id; }}

custom data

base constructor

Page 20: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

20

Throwing custom exception

• Can create and throw object of custom exception type– just like system exceptions

class Bank{ public void Withdraw(int id, double amount) { if (!accounts.Contains(id)) { throw new BadAccountException("Invalid account", id); } ... } ...}

check for validaccount number

create and throw

Page 21: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

21

Catching custom exception

• Custom exceptions caught by type– just like system exceptions

void Save(Bank b){ try { b.Withdraw(1234, 1000); } catch (BadAccountException e) { int i = e.id; string s = e.Message; }}

catch custom exception

custom data

from Exception

Page 22: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

22

Benefits

• Benefits of exception handling– decouples detection from handling– separates handler code– facilitates grouping and differentiation of conditions

Page 23: Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.

23

Summary

• Exceptions provide notification mechanism– allow clean separation of detection and handler code