Exception Handling
Exception Handling
Computer
Programming 1
Exception Handling
Introduction to Exception Handling
• When we write source code we expect errors during the compilation.
An exception is an occurrence of an undesirable situation that can be
detected during the program execution. For example, division by zero
is an exception, an array index that goes out of bound is an error.
Exception Handling (Division by 0)
• No Handling for Division by Zero
• No Error Checking Before
Performing Division
• No Mechanism to Recover from
Errors
• No Error Information
Approaches to Error Handling
• Ask the run-time environment to abort the program(# include
<cassert>)
• Use error checking( if else statements)
• Using function returning value for error checking
Ask the run-time environment to
abort the program and its issues.
• Program Still Crashes Instead of
Handling the Error Gracefully
• No Error Type
• But allows us to print a message
indicating the type of error.
Traditional Error Checking and Its
issues
• This code prevents crashing by
checking for division by zero
before performing the
operation. It avoids abrupt
termination and gives an error
message instead.
• Error handling mixed with
program logic
Error Checking Using a Function
Exception Handling in C++
• When a program encounters an • Key Concepts in Exception
unexpected situation (such as Handling in C++
division by zero), it should • try block: Contains the code that
handle the error gracefully might throw an exception.
instead of crashing. The best way
to manage runtime errors in C++ • throw statement: Used to signal
is by using exception handling an error when an issue occurs.
with try and catch blocks. • catch block: Handles the thrown
exception and prevents program
crashes.
How Exception Handling works in
C++.
• C++ utilizes what is called the • The second clause is called the
try-catch block. It is made up of catch clause, this lets the
two clauses. The first clause program handle the exception
includes the code that may and continue with the rest of the
cause the program to abort. If program if possible.
the error occurs the system
throws and exception (an object
of a fundamental type or class).
Syntax for Exception Handling in C+
+
Exception Handling (3 Patterns)
• In the first pattern, the try-catch
block is contained in the main
function. If an exception is
thrown the rest of the try clause
after the throw statement is
ignored and control moves to
the catch clause.
Code for the first pattern
Code for the second pattern
Code for the third pattern