Exception Handling
Exception Handling
Lecture 26
Exception Handling
R. BALASUBRAMANIAN
Computer Science and Engineering
1
Agenda
• Types of exceptions
• Try-catch blocks
• Custom exceptions
Exception Handling in C++/Java
• The exception handling in C++/java is one of the powerful mechanisms to
handle the runtime errors so that normal flow of the application can be
maintained.
• In C++/Java, exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
Introduction
• Errors in coding are categorized as:
– syntax errors –
compilation errors.
– Semantic/logical errors–
leads to programs producing unexpected output.
– runtime errors –
most often lead to abnormal termination of
programs or even cause the system to crash.
Exception Handling in C++
An exception is an issue that occurs during the execution of a program. In C++, an
exception is a mechanism to handle unexpected circumstances that arise while
the program is running, such as dividing by zero.
throw: An exception is thrown when a problem occurs, using the throw keyword.
catch: An exception is caught and handled at a specific point in the program with
an exception handler. The catch keyword is used to define this handler.
5
Common Runtime Errors:
• Dividing a number by zero.
• File errors:
• opening a file in “read mode” that does not exist or no
read permission
• Opening a file in “write/update mode” which has
“read only” permission.
8
9
C++ Standard Exceptions
10
C++ Standard Exceptions
Exception Description
===================================
std::exception An exception and parent class of all the standard C++ exceptions.
std::bad_alloc This can be thrown by new.
std::bad_cast This can be thrown by dynamic_cast.
std::bad_exception This is useful device to handle unexpected exceptions in a C++
program.
std::bad_typeid This can be thrown by typeid.
std::logic_error An exception that theoretically can be
detected by reading the code.
std::domain_error This is an exception thrown when a
mathematically invalid domain is used.
11
Exception Description
===================================
std::invalid_argument This is thrown due to invalid arguments.
std::length_error This is thrown when a too big std::string is created.
std::out_of_range This can be thrown by the at method from for example a
std::vector and std::bitset<>::operator[]().
std::runtime_error An exception that theoretically can not be detected by
reading the code.
std::overflow_error This is thrown if a mathematical overflow occurs.
std::range_error This is occured when you try to store
a value which is out of range.
std::underflow_error This is thrown if a mathematical
underflow occurs.
12
13
14
15
16
Thank You
17