Exception Handling in C++

Java exception handling is managed via five keywords: try, catch, throw, throws and finally. If an exception occurs in try block it is thrown.your code can catch this exception (using catch) and handle it in some rational manner.to manually throw an exception, use the keyword throw

syntax:
try{
//block of code to monitor for errors
}
catch(Exceptiontype1 exOb )
{
//exception handler for Exceptiontype1
}
finally
{
//block of code to be executed after try block ends
}
Exceptional Handling
Exceptional Handling

1.Example for exception handling:

#include <iostream> 
using namespace std; 
float division(int x, int y) { 
if( y == 0 ) { 
throw "Attempted to divide by zero!"; 
} 
return (x/y); 
} 
int main () { 
int i = 25; 
int j = 0; 
float k = 0; 
try { 
k = division(i, j); 
cout << k << endl; 
}catch (const char* e) { 
cerr << e << endl; 
} 
return 0; 
} 
 
Output: 
Attempted to divide by zero!
Translate »