6ebeeaa3d67511f9f985cb4f736cdcc8.ppt
- Количество слайдов: 9
Chapter 16 Exception Handling
What is Exception Handling? • A method of handling errors that informs the user of the problem and prevents the program from crashing. The program may terminate or do another action to handle the problem. • Throwing an exception: Either the standard libraries or your code signals an error. If it is a built-in exception, you can place code to “handle the exception” and allow for correction.
Exception-Handling with if-else statement #include
Exception Handling with try-throwcatch block #include
Define an exception class cout << donuts << " donuts. n" << milk << " glasses of milk. n" << "You have " << dpg << " donuts for each glass of milk. n"; } catch (No. Milk e) { cout << e. get. Donut() << “ donuts and NO milk!n” << “Go buy some milk. n”; } cout << “End of program. n"; #include
Define an exception class (cont. ) cout << donuts << " donuts. n" << milk << " glasses of milk. n" << "You have " << dpg << " donuts for each glass of milk. n"; } catch (No. Milk e) { cout << e. get. Donut() << “ donuts and NO milk!n” << “Go buy some milk. n”; } catch (Divide. By. Zero e) { cout << “Error! Divide By Zero n” << “ Exiting!n”; exit(1); } cout << “End of program. n"; #include
Multiple Throws and Catches • A try block can potentially throws any number of exception values. • Exception values can be different types. • However, only one exception can be thrown in 1 try block. • Each catch block can only catch values of 1 type. • There can be more than 1 catch block.
try-throw-catch syntax try { … //Some codes; throw (Data. Type 1 e_1); … //Some more codes throw (Data. Type 2 e_2); … //Some more codes throw (Data. Typen e_N); } catch (Data. Type 1 err 1) { … // Code for exception handler 1 } catch (Data. Type 1 err 2) { … // Code for exception handler 2 } catch (Data. Type 1 err. N) { … // Code for exception handler N } catch (…) … // Code for exception handler for anything not above }
Programming Techniques for Exception Handling • Include the try-throw within each function and the catch in a different function. • Every exception thrown must be caught somewhere in your code. Otherwise the std: : terminate() will be called and end your program. – You can nest try-catch blocks. – Don’t overuse. Write code that is robust and only use exceptions when necessary. • Better to avoid using exceptions except if knowing how and where the function is used determines how the exception is handled.