Exception Handling(1)
Exception Handling(1)
(24ECE2101)
Teaching Team
1
Introduction to Exception Handling
2.Asynchronous: Exceptions that are beyond the program’s control, such as disc
failure, keyboard interrupts, etc.
4
EXCEPTION HANDLING
2. catch in C++
The catch statement represents a block of code that is executed when a particular
exception is thrown from the try block. The code to handle the exception is written
inside the catch block.
3. throw in C++
An exception in C++ can be thrown using the throw keyword. When a program
encounters a throw statement, then it immediately terminates the current function
and starts finding a matching catch block to handle the thrown exception.
Note: Multiple catch statements can be used to catch different type of exceptions
thrown by try block.
The try and catch keywords come in pairs: We use the try
block to test some code and If the code throws an exception
we will handle it in our catch block.
EXCEPTION HANDLING
Handling of divide by 0 Exception
Implementation
Implementation
You can also use the throw keyword to output a reference number, like a
custom error number/code for organizing purposes (505 in our example):
Example explained
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:
Handling of Exceptions
Multiple Catch Blocks
Multiple Catch Blocks
a. catch(…)
b. catch()
c. catch(std::any_exception)
d. catch(std::exception)
Answer: a
Quiz Time
Answer: b
29
Quiz Time
Answer: a
30
Quiz Time
Answer: c
31
Quiz Time
a) Hello
b) Caught exception: 5
c) Compilation error
d) No output
Answer: b
Thanks
33