Exceptions
Outline
■ What is exception handling
■ Throwing and catching exceptions
■ Rethrowing exceptions
■ Declaring new exception types
■ Exceptions and polymorphism
Đại học Công nghệ - ĐHQG HN Exceptions 2
Error Handling int divide(int n, int d) {
return n/d;
}
What happens if d is zero? How to handle that?
■ Let it be?
■ Keep working with messed-up data?
■ Exit the program?
■ Too drastic
■ Displace an error message to users?
■ How? No idea
■ Notify the caller ?
■ Yes, I don’t know what to do, let those who know handle
the error
Đại học Công nghệ - ĐHQG HN Exceptions 3
Traditional int divide(int n, int d) {
if (d == 0) ……
Error Handling }
return n/d;
■ Return -1
■ Works in many cases
■ Does it work here?
■ Use global error codes
■ assign to a global error code variables
■ caller call a function to get the code
■ if the caller doesn’t handle the error, the program
crashes or continue running with bad data
Đại học Công nghệ - ĐHQG HN Exceptions 4
Modern: Exception
int divide(int n, int d) {
if (d == 0)
throw invalid_argument(“divide by zero”);
■ Return -1
return n/d;
} ■ Works in many cases
... ■ Does it work here?
int main() {
■ Use global error codes
try {
■ assign to a global
divide(10, 0); error code
//cause anvariables
exception to throw
}■ caller call a function to get the code
catch (invalid_argument& e) {
■ if the caller doesn’t handle the error, the program
cerr << e.what() << endl;
crashes
return or continue running with bad data
-1;
}
//...
}
Đại học Công nghệ - ĐHQG HN Exceptions 5
When calling a risky method
■ The method you're calling is risky and it could fail.
■ You need to know that the method you're calling is
risky
■ You then write code that handle the failure if it
happens. You need to be prepared, just in case.
Đại học Công nghệ - ĐHQG HN Exceptions 6
Exception - Concepts
■ Exception: an object containing information about an error,
which will be passed on to the code that handles it
❑ "Something bad happened. I failed!"
■ Thrown exception – an exception that has occurred
❑ ArithmeticException – can arise from a number of different
problems in arithmetic
❑ InputMismatchException – occurs when Scanner method
nextInt receives a string that does not represent an int
value
Đại học Công nghệ - ĐHQG HN Exceptions 7
try and catch try {
// code that might throw exceptions
}
catch (ExceptionTypeOne& e1) {
// exception-handling
■ Syntax: }
catch (ExceptionTypeTwo& e2) {
// exception-handling
}
■ Separate the code that describes what you want to do
(program logic) from the code that is executed when things go
wrong (error handing).
❑ try block – program logic
encloses code that might throw an exception and the code
that should not execute if an exception occurs
❑ catch block – error handling
catches (i.e., receives) and handles an exception,
Đại học Công nghệ - ĐHQG HN Exceptions 8
How try and catch work?
Đại học Công nghệ - ĐHQG HN Exceptions 9
Catching Exceptions
■ A catch block can catch exception of the declared type &
subclasses of the declared type
catch (logic_error& e) {…} can catch exceptions of type
logic_error,
invalid_argument, out_of_range, …
■ catch (...) catches everything that has not been caught
■ Uncaught exception – an exception that occurs for which
there are no matching catch blocks
❑ Cause the current program thread to terminate
Đại học Công nghệ - ĐHQG HN Exceptions 10
C++ Exceptions Hierarchy
■ All exceptions inherit either directly or indirectly from class Exception
■ Examples thrown by standard library
Can be inherited by custom exceptions:
Tham khảo: https://cppdeveloper.com/c-nang-cao/xu-ly-ngoai-le-exception-handling-trong-c/
Đại học Công nghệ - ĐHQG HN Exceptions 11
How to handle an exception?
■ A method has three choices:
1. catch and handle
2. pass it on to the method’s caller
3. catch, handle, then pass it on (rethrow)
Đại học Công nghệ - ĐHQG HN Exceptions 12
How to handle an exception?
■ A method has three choices:
1. catch and handle
2. pass it on to the method’s caller
3. catch, handle, then pass it on (rethrow)
■ How to handle an exception?
❑ try and catch blocks
Đại học Công nghệ - ĐHQG HN Exceptions 13
How to handle an exception?
■ A method has three choices:
1. catch and handle
2. pass it on to the method’s caller
3. catch, handle, then pass it on (rethrow)
Đại học Công nghệ - ĐHQG HN Exceptions 14
Đại học Công nghệ - ĐHQG HN Exceptions 15
How to handle an exception?
■ A method has three choices:
1. catch and handle
2. pass it on to the method’s caller
3. catch, handle, then pass it on (rethrow)
Đại học Công nghệ - ĐHQG HN Exceptions 16
Rethrowing Exceptions
■ Exceptions can be rethrown when a catch block decides
that…
❑ it cannot handle the exception, or
❑ it can process the exception only partially.
■ Example:
try {...
}
catch (exception& e) {
//do something;
throw;
}
Đại học Công nghệ - ĐHQG HN Exceptions 17
Declaring new exception types
class myexception: public exception {};
class myexception: public exception
{
virtual const char* what() const noexcept
{
return "My exception happened";
}
};
Đại học Công nghệ - ĐHQG HN Exceptions 18
Why using exceptions?
● Calling code have to recognize an error condition
and handle it.
● The exception can be propagated to the point in
the call stack that can handle the error.
● The exception stack-unwinding mechanism
destroys all objects in scope after an exception is
thrown, according to well-defined rules.
● Enables a clean separation between the code that
detects the error and the one handling the error.
19
Basic Guidelines
● Use asserts to check for errors that should never occur. Use exceptions to check for errors that
might occur, for example, errors in input validation on parameters of public functions. For more
information, see the Exceptions versus assertions section.
● Use exceptions when the code that handles the error is separated from the code that detects the
error by one or more intervening function calls. Consider whether to use error codes instead in
performance-critical loops, when code that handles the error is tightly coupled to the code that
detects it.
● For every function that might throw or propagate an exception, provide one of the three
exception guarantees: the strong guarantee, the basic guarantee, or the nothrow (noexcept)
guarantee. For more information, see How to: Design for exception safety.
● Throw exceptions by value, catch them by reference. Don’t catch what you can't handle.
● Don't use exception specifications, which are deprecated in C++11. For more information, see
the Exception specifications and noexcept section.
● Use standard library exception types when they apply. Derive custom exception types from the
exception Class hierarchy.
● Don't allow exceptions to escape from destructors or memory-deallocation functions
Source: Modern C++ best practices for exceptions and error handling
https://docs.microsoft.com/en-us/cpp/cpp/errors-and-exception-handling-modern-cpp
20