Chapter 10 Getting Started with Graphics Programming
Download
Report
Transcript Chapter 10 Getting Started with Graphics Programming
Chapter 13 Exception Handling
(异常处理)
§13.1 Introduction
§13.2 Exception Handling Mechanism
§13.3 Throwing Mechanisms
§13.4 Catching Mechanisms
§13.5 Rethrowing an Exception
§13.6 Specifying Exception
1
§13.1 Introduction
A program to read in two integers and displays
their quotient
Quotient
int main(){
cout << "Enter two integers: ";
int num1, num2;
cin >> num1 >> num2;
cout <<num1<<"/"<<num2<<" is "
<< (num1 / num2) << endl;
return 0;
}
Run
If you enter “0” for
num2, then?
A runtime error!
An exception!
2
What’s Exception?
Peculiar problems other than logic or syntax
errors
Run time anomalies or unusual conditions
Usually cause the program terminate abnormally
Including:
division by zero,
access to an array outside of its bounds, or
running out of memory or disk space,
etc.
3
Naive Exception Handling
Example of Integer Division
Adding an if statement to test the second number
if (num2 != 0){
cout <<num1 <<" / "<<num2<<" is "
<< (num1 / num2) << endl;
}else
cout << "Divisor cannot be zero"<<endl;
QuotientWithIf
Run
4
§13.2 Exception Handling Mechanism
Special Mechanism to detect, report and act
against exceptions.
Four tasks
Find the problem(Hit the exception)
Inform that an error has occurred (Throw the exception)
Receive the error information (Catch the exception)
Take corrective actions (Handle the exception)
5
Try-throw-catch
The try block:
Detects and throws
an exception
The throw statement:
To preface a block of
statements which may
generate exceptions.
try block
To report the exception by
throwing a object.
The catch block:
To catche the exception
thrown and take actions to
handle it.
Exception object
catch block
Catches and handles
the exception
6
C++ Exception Handling
Using try-throw-catch
int main(){
cout <<"Enter two integers: ";
int num1, num2;
QuotientWithException
cin >> num1 >> num2;
try{
if (num2 == 0) throw num1;
Run
cout << num1 << " / " << num2 << " is "
<< (num1 / num2) << endl;
}catch (int e){
cout << "Exception: an integer " << e <<
Exception
" cannot be divided by zero" << endl;
Handler
}
cout << "Execution continues ..." << endl;
}
7
Template for try-throw-catch
try
{
try
{
Code to try;
Throw an exception by “throw” or calling;
More code to try;
// ...
}
catch (type)
}
The rest code will NOT be executed
{
catch (type e)
if the exception occurs!
//…
{
}
Code to process the exception;
}
General
Parameter Omitted
Program 13.1.cpp.html
8
Advantages of C++ Exception Handling
int quotient(int num1, int num2){
if (num2 == 0)
throw num1;
return num1 / num2;
}
int quotient(int num1, int num2){
if (num2 != 0){
return num1 / num2;
}else
return -1;//?
}
C++ Exception Handling
Naive Exception Handling
•
•
More powerful:
- Can handle various cases
More structural
- Separate normal code and exception handling code
9
When to Use Exceptions
Yes!
• Common exceptions that may occur in multiple classes
• Unexpected error conditions
May be difficult to determine.
DO NOT abuse exception handling!
NO!
• Simple errors that may occur in individual functions
• Simple, expected situations
10
§13.3 Throwing Mechanism
Exception usually is thrown
by a function invoked inside
a try block.
Throw point
The point at which the throw
is executed
Upon exception
The control will jump to the
catch block, and
Cannot return back the throw
point.
Throw point
Function that causes
an exception
Invoke function
try block
Invokes a function that
contains an exception
Throw exception
catch block
Catches and handles
the exception
11
Exception from a Function
A program to compute quotient using a function
int quotient(int num1, int num2){
if (num2 == 0) throw num1;
return num1 / num2;
}
int main(){
//…
try{
int result = quotient(num1, num2);
//…
} catch (int e){
//…
}
//…
}
QuotientWithFunction
Run
12
Exception Classes
overflow_error
runtime_error
underflow_error
bad_alloc
bad_cast
exception
bad_type_id
bad_exception
invalid_argument
logic_error
length_error
out_of_range
13
Using Standard Classes
bad_alloc
bad_cast
runtime_error
ExceptionDemo1
Run
ExceptionDemo2
Run
ExceptionDemo3
Run
14
Customed Exception Classes
Use standard classes whenever possible
Create yours if necessary
An exception class is just like any C++ class
It is often desirable to derive it from exception
Directly or indirectly
To utilize the common features (e.g., the what()
function) in the exception class.
15
The Triangle Exception Class
GeometricObject
Triangle
-side1: double
-side2: double
TriangleException.h
Triangle.h
-side3: double
+Triangle()
+Triangle(side1: double, side2:
double, side3: double)
TestTriangle.cpp
+getSide1(): double
+getSide2(): double
+getSide3(): double
+setSide1(side1: double): void
+setSide2(side2: double): void
+setSide3(side3: double): void
Run
16
§13.4 Catching Mechanism
More than one exception in one try block?
One catch block can handle only one exception
try{
…
} catch (E e){
…
}
Program 13.3.cpp.html
try{
…
} catch (E1 e){
…
} catch (E2 e){
…
} catch (E3 e){
…
}
17
Example of Multiple Catches
Another type of exception in Triangle
class NonPositiveSideException: public logic_error{
public:
NonPositiveSideException(double side)
: logic_error("Non-positive side"){
this->side = side;
}
double getSide(){
return side;
}
private:
double side;
};
NonPositiveSideException.h
Run
NewTriangle.h
MultipleCatchDemo
18
Notes for Multiple Catches
If a catch block catches exception objects of a base
class, it can catch all the exception objects of the
derived classes of that base class.
So, a catch block for a base class type should appear
after a catch block for a derived class type.
try
{
...
}
catch (logic_error &ex)
{
...
}
catch (TriangleException &ex)
{
...
}
(a) Wrong order
try
{
...
}
catch (TriangleException &ex)
{
...
}
catch (logic_error &ex)
{
...
}
(b) Correct order
19
§14.5 Rethrowing an Exception
An exception can be rethrown
By a handler
For two reasons
The current handler cannot process the exception or
The current handler wants to let its caller be notified of the
exception.
The syntax:
try{
statements;
} catch (TheException &ex) {
perform operations before exits;
throw;
}
Program 13.5.cpp.html
20
Exception Propagation
function1
{
...
...
try
Invocation
try
{
{
...
...
invoke function1;
invoke function2;
statement1;
statement3;
}
}
catch (Exception1 &ex1)
catch (Exception2 &ex2)
{
{
Process ex1;
Process ex2;
Exception
}
}
statement2;
statement4;
}
}
int
function2
{
...
try
{
...
invoke function3;
statement5;
}
catch (Exception3 &ex3)
{
Process ex3;
}
statement6;
}
main() {
Exception
thrown in
function3
Call Stack
function3
main
function2
function2
function1
function1
function1
main
main
main
21
Exception Propagation
An exception that can’t be handled by any of a
function’s catch blocks is thrown to the caller
The exception is propagated along the reverse
order of the function calling
22
§14.6 Specifying Exception
What try-catch block should be provided in a
function?
Exceptions thrown by
The function itself
The functions called
What exceptions may be thrown by a function?
23
Exception Specification
Also known as throw list
lists exceptions that a function can throw
returnType functionName(parameterList)
throw (exceptionList);
Program 13.6.cpp.html
24
Two Special Lists
No throw list
May throw any exception!
returnType functionName(parameterList);
Empty throw list
Can’t throw any exception!
returnType functionName(parameterList) throw ();
25
Undeclared Exception
Throwing an exception not declared in the
throw list?
The function unexpected will be invoked!
A standard C++ function
Normally terminates the program
Visual studio doesn’t satisfy the throw list specification well.
26
Catch All Types of Exceptions
The exception type may not be able to anticipate
To force a catch block to catch all exceptions
thrown:
catch(…)
{
//Statements for processing
//all exceptions
}
Program 13.4.cpp.html
27
A Summary
Various exceptions may occur
try-throw-catch
Multiple catches
Propagation of exceptions
Standard exception classes
Customized exception classes
Rethrow
Exception specification
28