Simple Exception-Handling Example: Divide by Zero
- Keyword throw
- Throws an exception; Use when error occurs
- Can throw almost anything (exception object, integer, etc.); throw myObject;, throw 5;
- Exception objects
- Base class exception (
exception
)
- Constructor can take a string (to describe exception)
- Member function what() returns that string
- Upcoming example
- Handle divide-by-zero errors
- Define new exception class
- DivideByZeroException
- Inherit from exception
- In division function
- Test denominator
- If zero, throw exception (throw object)
- In try block
- Attempt to divide
- Have enclosing catch block; Catch DivideByZeroException objects
Figure 6.1:
Exception-handling example that throws exceptions on attempts to divide by zero. (Part 1 of 2)
|
Figure 6.2:
Exception-handling example that throws exceptions on attempts to divide by zero. (Part 2 of 2)
|
2004-12-28