Try Catch Block in C++
Here is the implementation of try catch block in C++ language:
// C++ program to demonstate the use of try,catch and throw
// in exception handling.
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
// try block
try {
int numerator = 10;
int denominator = 0;
int res;
// check if denominator is 0 then throw runtime
// error.
if (denominator == 0) {
throw runtime_error(
"Division by zero not allowed!");
}
// calculate result if no exception occurs
res = numerator / denominator;
//[printing result after division
cout << "Result after division: " << res << endl;
}
// catch block to catch the thrown exception
catch (const exception& e) {
// print the exception
cout << "Exception " << e.what() << endl;
}
return 0;
}
Output
Exception Division by zero not allowed!
Try Catch Block in Programming
In programming, a try catch block is used for exception handling. The try
block contains code that might throw an exception and the catch
block handles specific exceptions by providing custom code. It prevents program termination when exceptions occur. Remember, we can use a try
block without a catch
block, but not vice versa.
Table of Content
- What is a Try Block?
- What is a Catch/Except Block?
- Basic Syntax of Try Catch Block
- How to use Try Catch Block
- What is Nested Try Catch Block?
- Try Catch Block in C++
- Try Catch Block in Java
- Try Except Block in Python
- Try Catch Block in C#
- Best Practices of Try Catch Block
Contact Us