Chapter 16 Exception Handling 0 2018, SEU. All rights reserved. 1
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 1 Exception Handling Chapter 16
OBJECTIVES o What exceptions are and when to use them o To use Try, catch and throw to detect, handle and indicate exceptions, respectively. o To process uncaught and unexpected exceptions. o To declare new exception classes. o How stack unwinding enables exceptions not caught in one scope to be caught in another Scope o To handlle new failures o To use auto_ptr to prevent memory leaks To understand the standard exception hierarchy. 0 2018, SEU. All rights reserved. 2
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 2 OBJECTIVES What exceptions are and when to use them. To use Try, catch and throw to detect, handle and indicate exceptions, respectively. To process uncaught and unexpected exceptions. To declare new exception classes. How stack unwinding enables exceptions not caught in one scope to be caught in another scope. To handle new failures. To use auto_ptr to prevent memory leaks. To understand the standard exception hierarchy
Topics o 16.1 Introduction o 16.2 Exception-Handling overview 16.3 Example: Handling an Attempt to Divide by Zero o 16.4 When to Use Exception Handling o 16.5 Rethrowing an Exception 16.6 Exception Specifications o 16.7 Processing Unexpected Exceptions o16.8 Stack Unwinding 16.9 Constructors, Destructors and Exception Handling o 16.10 Exceptions and Inheritance o 16.11 Processing new Failures 0 2018, SEU. All rights reserved. 3
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 3 Topics 16.1 Introduction 16.2 Exception-Handling Overview 16.3 Example: Handling an Attempt to Divide by Zero 16.4 When to Use Exception Handling 16.5 Rethrowing an Exception 16.6 Exception Specifications 16.7 Processing Unexpected Exceptions 16.8 Stack Unwinding 16.9 Constructors, Destructors and Exception Handling 16.10 Exceptions and Inheritance 16.11 Processing new Failures
16.1 Introduction 大型程序往往会产生一些很难查找的甚至是无法 避免的运行时错误。 ●当发生运行时错误时,不能简单地结束程序运行, 而是需要指出错误,并由用户决定下一步工作。 面向对象的异常处理( exception handling)机 制是C++语言用以解决这个问题的有力工具。 0 2018, SEU. All rights reserved. 4
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 4 16.1 Introduction 大型程序往往会产生一些很难查找的甚至是无法 避免的运行时错误。 当发生运行时错误时,不能简单地结束程序运行, 而是需要指出错误,并由用户决定下一步工作。 面向对象的异常处理(exception handling)机 制是C++语言用以解决这个问题的有力工具
16.1 Introduction °异常( exception)是程序可能检测到的,运行时 不正常的情况,如存储空间耗尽、数组越界、被0 除等等。 °特点:可以预见可能发生在什么地方,但是无法 确知怎样发生和何时发生。 °在一个大型的程序(软件)中,程序各部分是由不同的 小组编写的,它们由公共接口连起来,错误可能就发生 在相互的配合上,也可能发生在事先根本想不到的个别 的条件组合上 0 2018, SEU. All rights reserved. 5
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 5 16.1 Introduction 异常(exception)是程序可能检测到的,运行时 不正常的情况,如存储空间耗尽、数组越界、被0 除等等。 特点:可以预见可能发生在什么地方,但是无法 确知怎样发生和何时发生。 在一个大型的程序(软件)中,程序各部分是由不同的 小组编写的,它们由公共接口连起来,错误可能就发生 在相互的配合上,也可能发生在事先根本想不到的个别 的条件组合上