Exception Handling
Introduction to Exception Handling
Exception handling in C++ provides a mechanism to deal with runtime errors or exceptions. In simple terms, an exception is a problem that arises during the execution of a program. This tutorial will provide you with a clear understanding of exception handling, its types, and how to use it in your C++ programs.
What is an Exception?
In C++, an exception is a runtime error or an abnormal condition that disrupts the normal flow of the program. When an exception occurs, the current function stops executing and control transfers to a specific part of the code which is designed to handle that exception.
Types of Exceptions
There are two types of exceptions in C++:
- Synchronous Exceptions: These are exceptions triggered by the system and are caused by programming errors. Examples include division by zero, dereferencing a null pointer, etc.
- Asynchronous Exceptions: These are exceptions triggered by external events such as a signal from the operating system.
Exception Handling Mechanism
In C++, there are three keywords used for exception handling: try
, catch
, and throw
.
- Throw: Program throws an exception when a problem is detected. This is done using the
throw
keyword. - Catch: The
catch
block is used to handle the exception. It follows thetry
block. - Try: Any code that might throw an exception is put in the
try
block.
Here is the basic syntax of exception handling in C++:
try {
// code here
}
catch (ExceptionType1 ex1) {
// code to handle exception ex1
}
catch (ExceptionType2 ex2) {
// code to handle exception ex2
}
// you can have multiple catch blocks
Example
Let's look at an example of exception handling:
#include <iostream>
using namespace std;
int main() {
try {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
if (num2 == 0) {
throw "Division by zero is not possible!";
}
else {
cout << "The quotient is " << num1 / num2 << endl;
}
}
catch (const char* ex) {
cout << "Error: " << ex << endl;
}
return 0;
}
In the above example, the program asks the user to input two numbers. If the user enters zero as the second number, division by zero will occur, which is an error. So, the program throws an exception using the throw
keyword and the exception is caught and handled using the catch
block.
Conclusion
Exception handling in C++ allows us to control the program flow and handle runtime errors efficiently. It provides a clear and structured approach to control complex error handling. It is an essential concept to master as it helps in creating robust and error-free code.