31
Exception Handling

Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Embed Size (px)

Citation preview

Page 1: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Exception Handling

Page 2: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Introduction

• One benefit of C++ over C is its exception handling system.

• An exception is a situation in which a program has an unexpected circumstance that the section of code containing the problem is not explicitly designed to handle.

• Exception handling is useful because it makes it easy to separate the error handling code from the code written to handle the chores of the program.

• Doing so also makes reading and writing the code easierAs a programmer, you should anticipate any abnormal behavior that could be caused by the user entering wrong information that could otherwise lead to unpredictable results.

Page 3: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

An Exception Example

• Imagine: people rarely run out of milk:cout << "Enter number of donuts:";cin >> donuts;cout << "Enter number of glasses of milk:";cin >> milkdpg = (double)donuts/double(milk);cout << donuts << "donuts.\n";

<< milk << "glasses of milk.\n";<< "You have " << dpg << "donuts for each glass of milk.\n";

• Basic code assumes never run out of milk

Page 4: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

An Exception Example• However, if one day you run out of milk, i.e. milk=0, then the

following line of code has an issuedpg = (double)donuts/double(milk); // divided by zero!

• Program should accommodate unlikelysituation of running out of milk– Can use simple if-else structure:

if (milk <= 0)cout << "Go buy some milk!\n";

else{…}

• Notice: this is NOT an exception-handling, because it is in the regular part of the program!

Page 5: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Toy Example with Exception Handling: Display 18.2

18-5Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Exception Handlingcout <<“…”;cin >> donuts;cout << “…”;cin >> milk;

if (milk <=0) cout << “Go buy some milk!” <<endl;else{ …}…

Not an exception handling!

Page 6: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Toy Example Discussion

• Code between keywords try and catch– Same code from ordinary version, except

if statement simpler:if (milk <= 0)

throw donuts;

– Much cleaner code– If "no milk" do something exceptional

• The "something exceptional" is providedafter keyword catch

18-6Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 7: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Toy Example try-catch

• Try block– Handles "normal" situation

• Catch block– Handles "exceptional" situations

• Provides separation of normal from exceptional– Not big deal for this simple example, but

important concept18-7Copyright © 2010 Pearson Addison-Wesley.

All rights reserved.

Page 8: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

try block

• Basic method of exception-handling istry-throw-catch

• Try block:try{

Some_Code;}– Contains code for basic algorithm when all

goes smoothly

18-8Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 9: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

throw

• Inside try-block, when something unusual happens:

• try{

Code_To_Tryif (exceptional_happened)

throw donuts;More_Code…

}

– Keyword throw followed by exception type– Called "throwing an exception"

18-9Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 10: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

catch-block

• When something thrown goes somewhere– In C++, flow of control goes from try-block to

catch-block• try-block is "exited" and control passes to catch-block

– Executing catch block called "catching the exception"

• Exceptions must be "handled" in some catch block

18-10Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 11: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

cout <<“…”;cin >> donuts;cout << “…”;cin >> milk;

if (milk <=0) cout << “Go buy some milk!” <<endl;else{ …}More_code … // will be executed

Not an exception handling! Exception Handling

try{

cout <<“…”;cin >> donuts;cout << “…”;cin >> milk;

if (milk <=0) throw donuts;else{ …}More_code … // will NOT be executed

}

catch (int e){

cout << “Go buy some milk!” <<endl;}

Page 12: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

catch-block More

• Recall:catch(int e){

cout << e << " donuts, and no milk!\n";<< " Go buy some milk.\n";

}

• Looks like function definition with int parameter!– Not a function, but works similarly– throw is like a "function call"

18-12Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 13: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

catch-block Parameter

• Recall: catch(int e)

• "e" called catch-block parameter, i.e. type of the errors– Each catch block can have at most ONE

catch-block parameter

• Does two things:1. type name specifies what kind of thrown

value the catch-block can catch2. Provides name for thrown value caught;

can "do things" with value

18-13Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 14: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Show examples

Page 15: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Defining Exception Classes

• throw statement can throw value of any type

• Exception class– Contains objects with information to

be thrown– Can have different types identifying each

possible exceptional situation– Still just a class• An "exception class" due to how it’s used

18-15Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 16: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Exception Class for Toy Example

• Consider:class NoMilk{public:

NoMilk() { }NoMilk(int howMany) : count(howMany) { }int getcount() const { return count; }

private:int count;

};

• throw NoMilk(donuts);– Invokes constructor of NoMilk class

18-16Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 17: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Trivial Exception Classes

• Consider:class DivideByZero{ };

• No member variables• No member functions (except default

constructor)• Nothing but it’s name, which is enough– Might be "nothing to do" with exception value– Used simply to "get to" catch block– Can omit catch block parameter

18-17Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 18: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Show examples

Page 19: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Multiple Throws and Catches

• try-block typically throws any number ofexception values, of differing types, at different places

• Of course only one exception thrown– Since throw statement ends try-block

• But different types can be thrown– Each catch block only catches "one type"– Typical to place many catch-blocks after each

try-block• To catch "all-possible" exceptions to be thrown

18-19Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 20: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Catching• Order of catch blocks important

– More specific exception types go first!

• Catch-blocks tried "in order" after try-block– First match handles it! Be careful the inheritance relation between

different exception classes!

• Consider:catch (…) { }– Called "catch-all", "default" exception handler– Catches any exception– Ensure catch-all placed AFTER more specific

exceptions!• Or others will never be caught!

18-20Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 21: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Throwing Exception in Function

• Function might throw exception

• Callers might have different "reactions"– Some might desire to "end program"– Some might continue, or do something else

• Makes sense to "catch" exception incalling function’s try-catch-block– Place call inside try-block– Handle in catch-block after try-block

18-21Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 22: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Throwing Exception in Function Example

• Consider:try{

quotient = safeDivide(num, den);}catch (DivideByZero){ … }

• safeDivide() function throws DividebyZeroexception– Handled back in caller’s catch-block

18-22Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 23: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Show the example of throwing exception inside a function

Page 24: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Preferred throw-catch Triad: throw

• void functionA() throw (MyException){

…throw MyException(arg);…

}

• Function throws exception as needed

18-24Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 25: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Preferred throw-catch Triad: catch

• Then some other function:void functionB(){

…try{

…functionA();…

}catch (MyException e){ // Handle exception }…

}

18-25Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 26: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Uncaught Exceptions

• Should catch every exception thrown

• If not program terminates– terminate() is called

• Recall for functions– If exception not in throw list: unexpected()

is called• It in turn calls terminate()

• So same result18-26Copyright © 2010 Pearson Addison-Wesley.

All rights reserved.

Page 27: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Overuse of Exceptions

• Exceptions alter flow of control– Similar to old "goto" construct– "Unrestricted" flow of control

• Should be used sparingly

• Good rule:– If desire a "throw": consider how to write

program without throw– If alternative reasonable do it

18-27Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 28: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Summary 1

• Exception handling allows separation of"normal" cases and "exceptional" cases

• Exceptions thrown in try-block– Or within a function whose call is in try-block

• Exceptions caught in catch-block

• try-blocks typically followed by more thanone catch-block– List more specific exceptions first

18-28Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 29: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

Summary 2• Best used with separate functions

– Especially considering callers might handle differently

• Exceptions thrown in but not caught infunction, should be listed in throw list

• Exceptions thrown but never caught program terminates

• Resist overuse of exceptions– Unrestricted flow of control

18-29Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 30: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

What is the output of the following program under the given input?

class DivideExp{public: DivideExp(double in=0) : divisor (in) {} double divisor;};

class DivideByZero : public DivideExp{public: DivideByZero(double in=0) : DivideExp(in) {}};

class DivideByNeg: public DivideExp{public: DivideByNeg(double in=0) : DivideExp(in) {}};

void main(){

try{

cout <<“input num1:”;cin >> num1;cout << “input num2: ”;cin >> num2;

if (num2 == 0) throw DivideByZero(num1);else if (num2 < 0) throw DivideByNeg(num1);else{ cout <<“num1/num2=“<<num1/num2<<endl;}cout << “succeeded!” << endl;

}catch (DivideByZero e){ cout << e.divisor << “divided by zero!” <<endl;}catch (DivideExp e){ cout << e.divisor << “divided by invalid value!”<<endl;}catch (DivideByNeg e){ cout << e.divisor << “divided by negative value!”<<endl;}catch (…){ cout << “Unknown exception!” << endl;}

}

input 1: 4, 2input 2: 5, 0input 3: 0, -1

Page 31: Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected

What is the output of the following program under the given input?

class DivideExp{public: DivideExp(double in=0) : divisor (in) {} double divisor;};

class DivideByZero : public DivideExp{public: DivideByZero(double in=0) : DivideExp(in) {}};

class DivideByNeg: public DivideExp{public: DivideByNeg(double in=0) : DivideExp(in) {}};

void main(){

try{

cout <<“input num1:”;cin >> num1;cout << “input num2: ”;cin >> num2;

if (num2 == 0) throw DivideByZero(num1);else if (num2 < 0) throw DivideByNeg(num1);else{ cout <<“num1/num2=“<<num1/num2<<endl;}cout << “succeeded!” << endl;

}catch (DivideByZero e){ cout << e.divisor << “divided by zero!” <<endl;}catch (DivideExp e){ cout << e.divisor << “divided by invalid value!”<<endl;}catch (DivideByNeg e){ cout << e.divisor << “divided by negative value!”<<endl;}catch (…){ cout << “Unknown exception!” << endl;}

}

succeeded!5 divided by zero!0 divided by invalid value!