100% found this document useful (1 vote)
2 views15 pages

Exception Handling in C++

This document explains exception handling in C++, which involves managing unexpected errors during program execution using the keywords try, throw, and catch. It highlights the advantages of exception handling over traditional error handling, such as improved code readability and the ability to group error types. Additionally, it outlines best practices for implementing exception handling effectively to avoid common mistakes.

Uploaded by

meng053116
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2 views15 pages

Exception Handling in C++

This document explains exception handling in C++, which involves managing unexpected errors during program execution using the keywords try, throw, and catch. It highlights the advantages of exception handling over traditional error handling, such as improved code readability and the ability to group error types. Additionally, it outlines best practices for implementing exception handling effectively to avoid common mistakes.

Uploaded by

meng053116
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Exception Handling in C++

WHAT ARE EXCEPTIONS?

 In C++, exceptions are unexpected problems or errors that occur while a


program is running. For example, in a program that divides two numbers, dividing
a number by 0 is an exception as it may lead to undefined errors.

 The process of dealing with exceptions is known as exception handling. It allows


programmers to make the program ready for any errors that may happen during
execution and handle them gracefully so that it keeps running without errors.

 Exception handling in C++ consist of three keywords: try, throw and catch.
C++ TRY, THROW AND CATCH

 The try statement allows you to define a block of code to be tested for errors
while it is being executed.

 The throw keyword throws an exception when a problem is detected, which lets
us create a custom error.

 The catch statement allows you to define a block of code to be executed, if an


error occurs in the try block.
 The try and catch keywords come in pairs.
Syntax:
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
 We use the try block to test some code: If the age variable is less than 18, we will
throw an exception, and handle it in our catch block.

 In the catch block, we catch the error and do something about it. The catch
statement takes a parameter: in our example we use an int variable (myNum)
(because we are throwing an exception of int type in the try block (age)), to
output the value of age.

 If no error occurs (e.g. if age is 20 instead of 15, meaning it will be be greater than
18), the catch block is skipped.
 We use the try block to test some code: If the age variable is less than 18, we will
throw an exception, and handle it in our catch block.

 In the catch block, we catch the error and do something about it. The catch
statement takes a parameter: in our example we use an int variable (myNum)
(because we are throwing an exception of int type in the try block (age)), to
output the value of age.

 If no error occurs (e.g. if age is 20 instead of 15, meaning it will be greater than
18), the catch block is skipped.

 You can also use the throw keyword to output a reference number, like a custom
error number/code for organizing purposes.
Handle Any Type of Exceptions (...)

 If you do not know the throw type used in the try block, you can use the "three dots"
syntax (...) inside the catch block, which will handle any type of exception.
Throwing Standard Exceptions

The below image shows standard exceptions


hierarchy in C++:
 Standard exceptions are the set of classes
that represent different types of common
exceptions.
 All these classes are defined inside
<stdexcept> header file and mainly
derived from std::exception class which
act as the base class for inbuilt
exceptions.
 These exceptions are thrown by C++ library components so we should know how
to handle them. The what() method is present in every standard exception to
provide information about the exception itself.

 When the standard exceptions cannot satisfy our requirement, we can create a
custom exception class. It is recommended to inherit standard exception in this
class to provide seamless integrity with library components though, it is not
compulsory.
Why do we need Exception Handling in C++?

Errors or abnormal conditions can also be handled without exception handling, like it is done
in C using conditional statements. But an exception handling provides the following
advantages over traditional error handling:

 Separation of Error Handling Code from Normal Code: There are always if-else conditions
to handle errors in traditional error handling codes. These conditions and the code to
handle errors get mixed up with the normal flow. This makes the code less readable and
maintainable. With try and catch blocks, the code for error handling becomes separate
from the normal flow.
 Functions/Methods can handle only the exceptions They choose: A function can
throw many exceptions but may choose to handle some of them. The other
exceptions, which are thrown but not caught, can be handled by the caller. If
the caller chooses not to catch them, then the exceptions are handled by the
caller of the caller.

 In C++, a function can specify the exceptions that it throws using the throw
keyword. The caller of this function must handle the exception in some way
(either by specifying it again or catching it).

 Grouping of Error Types: In C++, both basic types and objects can be thrown as
exceptions. We can create a hierarchy of exception objects, group exceptions in
namespaces or classes, and categorize them according to their types.
Best Practices of Exception Handling

Exception handling in C++ is a useful tool to make a robust program but there are several
common mistakes to avoid when implementing exception handling in our programs. So,
there are some best practices that should be followed in exception handling:

 Don't use exceptions for regular control flow. Only use them for exceptional situations
(errors).
 Catch exceptions by reference whenever possible to avoid copying overhead and
enable polymorphic selection.
 Always catch exceptions by reference to a constant to avoid accidental modification.
 Catching generic exceptions using catch(...) does not provide information about
exception type, so better to catch specific exceptions to handle errors
appropriately.

 Failing to catch exceptions can cause the program to terminate unexpectedly.


Always ensure exceptions are caught and handled properly to maintain stability.

 Not releasing resources (e.g., memory, file handles) after an exception can led to
resource leaks. Use proper cleanup mechanisms such as RAII or finally blocks.

You might also like