Exception Handling
exceptions are runtime anomalies or abnormal conditions that a program encounters
during its execution. The process of handling these exceptions is called exception
handling. Using the exception handling mechanism, the control from one part of the
program where the exception occurred can be transferred to another part of the code.
An exception is an unexpected problem that arises during the execution of a program
our program terminates suddenly with some errors/issues. Exception occurs during
the running of the program (runtime).
Types of C++ Exception
1. try in C++
The try keyword represents a block of code that may throw an exception
placed inside the try block. It’s followed by one or more catch blocks. If an
exception occurs, try block throws that exception.
General Syntax:
try {
// code that may raise an exception
throw argument;
}
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.
General Syntax:
catch (exception) {
// code to handle exception
}
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.
General Syntax:
try {
// code that may raise an exception
throw argument;
}