tailieunhanh - Chapter 18 Exception Handling
Exception Handling typically throws any number of exception values, of differing types ,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. | Chapter 18 Exception Handling Learning Objectives Exception Handling Basics Defining exception classes Multiple throws and catches Exception specifications Programming Techniques for Exception Handling When to throw exceptions Exception class hierarchies Introduction Typical approach to development: Write programs assuming things go as planned Get "core" working Then take care of "exceptional" cases C++ exception-handling facilities Handle "exceptional" situations Mechanism "signals" unusual happening Another place in code "deals" with exception Exception-Handling Basics Meant to be used "sparingly" In "involved" situations Difficult to teach such large examples Approach: Simple "toy" examples, that would not normally use exception-handling Keep in mind "big picture" Toy Example Imagine: people rarely run out of milk: cout > donuts; cout > milk dpg = donuts/static_cast(milk); cout > donuts; cout > milk dpg = donuts/static_cast(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 Toy Example if-else Notice: If no milk divide by zero error! Program should accommodate unlikely situation of running out of milk Can use simple if-else structure: if (milk <= 0) cout << "Go buy some milk!\n"; else { } Notice: no exception-handling here Toy Example with Exception Handling: Display Same Thing Using Exception Handling 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 provided after keyword catch 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 concept try block Basic method of .
đang nạp các trang xem trước