You are on page 1of 11

Exception Handling in C++

Error Handling

Dr. K. Veningston
Department of Computer Science and Engineering
National Institute of Technology Srinagar
veningstonk@nitsri.ac.in
Exception Handling
• C does not provide direct support to error handling (or
exception handling)
• There are ways through which error handling can be done in C
Exception Handling in C++
• An exception is a problem that arises during the execution of a
program.
– A block of code that causes trouble for the compiler.
– Due to the exception, the program/server may stop abruptly. So, the
program will no longer be running.
• A C++ exception is a response to an exceptional circumstance that
arises while a program is running.
• C++ exception handling is built upon 3 keywords.
– try
– catch, and
– throw
Exception Handling in C++
• throw
– A program throws an exception when a problem shows up. This is done
using a throw keyword.
• catch
– A program catches an exception with an exception handler at the place in a
program where you want to handle the problem.
– The catch keyword indicates the catching of an exception.
• try
– A try block identifies a block of code for which particular exceptions will be
activated.
– It is followed by one or more catch blocks.
Exception Handling in C++
• Exception handling helps us handle this situation to avoid this
kinds of circumstances.
… What if d becomes 0 while running the code?
• Server may stop if we do not handle this
try { case/condition.
… • Program is expected to throw an exception to the
These lines are
prone to Error.
b = c / d * c; catch block, if we write it in a try block.

throw


} catch {
Handles exception if anything wrong happens in the
// Error handling code
lines that are prone to Error.
}
Exception Handling in C++ - Example

try {

// protected code A class in C++
if anything wrong …
happens in the } catch (ExceptionName e1){
protected code, try // catch block
block will throw it to a
} catch (ExceptionName e2){ • We can have different
particular catch block // catch block types of Exceptions
that Error belongs to.
} • e1, e2,…, eN are
… objects of class
catch (ExceptionName eN){ Exception
// catch block
}
Exception Handling in C++ - User-defined Exception
Exception Handling in C++ - User-defined Exception

A separate
iostream for
outputting error
messages on
Error Console.
Exception Handling in C++ - Exercise 1

Anything after throw


statement does not work.
Exception Handling in C++ - Exercise 2

• Nested try blocks


• This line/Exception belongs to
both the try blocks.
• This throw will be caught by
catch block of both the try
blocks.

You might also like