1. Trang chủ
  2. » Công Nghệ Thông Tin

bài giảng chú giải trình hướng đối tượng bài 3

44 311 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 44
Dung lượng 737 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The Throw-Catch Gamecatch throw return call • Error handling is a path parallel to the return path • When a throw is activated stack unwinding occurs and destructors are activated • If,

Trang 1

UNIT-III

Trang 2

 Easily create a large range of related functions or classes

 Function template - the blueprint of the related functions

Template function - a specific function made from a

function template

 Class templates

 Allow type-specific versions of generic classes

 Syntax for class template:

Trang 3

Function templates

Syntax:

template<class type> function_declaration; Or-

template<typename type> function_declaration;

 Function templates are special functions that can operate with

generic types This allows us to create a function template

whose functionality can be adapted to more than one type or class without repeating the entire code for each type.

In C++ this can be achieved using template parameters A

template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function

parameters can be used to pass values to a function, template parameters allow to pass also types to a function These

function templates can use these parameters as if they were any other regular type

Trang 4

declaring function templates

 template <class identifier>

Trang 5

}

Trang 6

cout << n << endl;

return 0;

}

Trang 8

template <class T>

T mypair<T>::getmax () {

T retval;

retval = a>b? a : b;

return retval;

}

Trang 10

Introduction to Exception

Handling

• An exceptionexception is any unusual event, either

erroneous or not, detectable by either hardware or software, that may require special processing

• Without exception handlingexception handling

– When an exception occurs, control goes to the

operating system, where typically

• an error message is displayed

• the program is terminated

• With exception handling

– Programs are allowed to trap exceptions

– There is a possibility to fix the problem and continuing execution

Trang 11

The Throw-Catch Game

catch

throw

return call

• Error handling is a path parallel to the return path

• When a throw is activated stack unwinding occurs and destructors are activated

• If, during a throw, a destructor throws additional exception

std::terminate() is called

• we cannot handle two exceptions

Trang 12

 Lets consider class stack

const int MAX_ELEM=10;

template < typename T, int size=MAX_ELEM>

Trang 13

Class Anomalies

 What happens if we pop() an empty stack?

 What happens if we push() on a full stack?

 We decide that these situations need to be handled in a special manner, since they are anomalies of the class behavior

 First we define classes of exceptions which may be thrown

 Upon anomaly detection, we will throw an exception

class popOnEmpty { /* … */ }

class pushOnFull { /* … */ }

Trang 14

Exception Handling Syntax

Trang 15

 No need to examine the returned value for checking for success.

};

Trang 16

Try…Catch BlocksWrap the code which needs to be “exception

sensitive”, and react to raised exceptions, in a try {…} catch {…} blocks

 The client’s code look now as following

Trang 17

Try…Catch Blocks

 When exception is thrown, execution resumes in the

“closest” catch clause handling the exception

 If no catch clause exists capable of handling the

exception, program execution resumes at the

terminate() function

 Variables declared within the try block cannot be

referred to at the catch clause, since they are local to the block

Trang 18

try catch syntax

Form is:

try { // code

}

catch (ExceptionType_1 e)

{ handle exception 1}

catch (ExceptionType_2 e) { handle exception 2 }

catch (ExceptionType_N e) { handle exception N }

Trang 19

Throwing Objects

 Additional data encapsulated

 An object is created upon invoking the throw statement

 Can be created with additional data, passed

to Ctor

 Object is destroyed after the catch clause

ends

Trang 20

 Lifetime of local variables ends

 Destructors are called

 If no handler is supplied, terminate() terminate() is called

 Since exception is a situation, where the program

cannot continue execution in a normal manner

 By default terminate() terminate() calls abort() abort()

 Similar to function call behavior

 But information to set up a function call is not

available at compile time, run-time support is needed

Trang 21

Re-throwing and Catch All

After some corrective action, a catch clause may throw an exception to be further handled, passing the exception

to another catch clause, by throw

}

Trang 22

Re-throwing and Catch All

General exception handling can be

catch (popOnFull e) {

// something }

catch (…) { // handle every exception

// something }

Trang 23

Exception Specification

Function interface need to be as precise

as possible, it is the contract between

several codes

Client code may need to prepare for

specific handling

Best is to provide exception

specification with the method

declaration

 This will help the compiler to check

consistency, to check that no other exceptions are thrown

 It follows the function parameter list

Trang 25

Nesting try Blocks

handled by closest matching handler

Trang 26

Exceptions from Function Calls

 No different from nested try blocks

 Auto variables on stack are destroyed

 Exception jumps to nearest handler

 Allows exception handlers to be implemented far away from where the problem was

 May requires a knowledge of the issue

packaged in exception object for appropriate

handling

Trang 27

Exception Hierarchies

 Class types representing exceptions may be

organized into groups or hierarchies

class exception {}

class stackExcp : public exception {}

class popOnEmpty : public stackExcp {}

class pushOnFull : public stackExcp {}

 Throwing an exception of type popOnEmpty may

be caught by a handler expecting its base

 Therefore order should be handling more concrete types, and then handling more generic types

 Since handling is evaluated in order of specification, “first match”

 Ctors and Dtors are called in order like before

Trang 28

Standard Exception

exception

overflow_error underflow_error

range_error invalid_argument

out_of_range length_error

domain_error

runtime_error logic_error

bad_typeid bad_cast

ios_base::failure

bad_alloc bad_exception

Trang 32

1 // A simple exception-handling example that checks for

2 // divide-by-zero exceptions

3 #include <iostream>

4 #include <exception>

5 using namespace std;

6

7 // DivideByZeroException objects should be thrown by

8 // functions upon detecting division-by-zero exceptions

9 class DivideByZeroException : public exception {

10

11 public:

12

13 // constructor specifies default error message

14 DivideByZeroException()

15 : exception( "attempted to divide by zero" ) {}

16

17 }; // end class DivideByZeroException

Define new exception class

(inherit from exception)

Pass a descriptive message to the constructor.

Exceptions Example

Trang 33

18 // perform division and throw DivideByZeroException object if

• // divide-by-zero exception occurs

• double quotient( int numerator, int denominator ) throw

26 // return division result

27 return static_cast < double >( numerator ) / denominator;

28 } // end function quotient

29

30 int main()

31 {

32 int number1; // user-specified numerator

33 int number2; // user-specified denominator

34 double result; // result of division

Trang 34

38 while ( cin >> number1 >> number2 ) {

39 // try block contains code that might throw exception

40 // and code that should not execute if an exception occurs 41 try {

42 result = quotient( number1, number2 );

43 cout << "The quotient is: " << result << endl ;

44 } // end try

45 // exception handler handles a divide-by-zero exception 46 catch ( DivideByZeroException &divideByZeroException ) { 47 cout << "Exception occurred: "

48 << divideByZeroException.what() << endl ;

49 } // end catch

50

51 cout << "\nEnter two integers (end-of-file to end): " ;

52 } // end while

53 cout << endl ;

54 return 0;

55 } // end main

Exceptions Example

catch (exception& e) {

cout << “Exception occurred: “

<< e.what() << endl ; }

Trang 35

Enter two integers (end-of-file to end): 100 7 The quotient is: 14.2857

Enter two integers (end-of-file to end): 100 0 Exception occurred: attempted to divide by zero Enter two integers (end-of-file to end): ^Z

Exceptions Example

Trang 36

When To Use Exceptions

 Fix the problem and try again

 Patch the problem and continue

 Make code safer (catch fatal errors)

Trang 37

Form of catch

catch (type parm){stmts}

Parameter is any type

The catch matches the type of the

Trang 38

Catch Parameter

Needs to match the throw parameter

Carries information from the site of the error to the catch clause

Any type may be thrown and later

caught

System errors are usually char *

The error type of an elipsis will catch anything:

catch(…) { }

 but gives no information

Trang 39

Exceptions and the

string, which is the message

Trang 40

Throwing an Exception

 Example:

if(j==0)

throw “j was zero\n”;

User defined throws may place a suffix

on the function:

int func(…) throw (char *) {

 indicates the exceptions that could be thrown

Trang 41

Cause and Effect

The throw and catch do not have to be near each other

The throw is like a super return

The current function is exited as well as any between this one and the function

containing the try and catch

Consider in next screen, a main function

with a try catch that calls Fun_1, which

calls Fun_2, which calls Oops, which

throws an exception

Trang 42

Nested Trys

We do not usually nest a try within

another

However, to get to our exception we

may go through several try catch pairs

Trang 43

Multiple Catches

catch clauses

 They are tried in order from top to bottom

 What the clause handles is based on the type of the parameter to the catch

 The first one that matches handles the

error

Trang 44

The Catch Parameter Type

 Two catch parameters of different types

usually cannot interfere with each other

 Thus the order of:

catch (int ie) {…}

catch (char * ce) {…}

does not matter

 This is not true if the parameters are in the same inheritance hierarchy

Ngày đăng: 24/10/2014, 16:24

TỪ KHÓA LIÊN QUAN

🧩 Sản phẩm bạn có thể quan tâm

w