Catch all exceptions

Catch all exceptions :- In some cases there is no need to write various catch blocks for various types of exceptions rather all types of exceptions are handled by a single catch block. It is called one catch block for all exception.
Syntax :- catch (...){
                statements;
               .............
               .............
               }

Example:-
C++ program to catch all exception in one catch block in exception handling.
#include<iostream.h>
#include<conio.h>
void test(int x){
try{
if(x==1) throw 5; //int
if(x==0) throw 'e'; //char
if(x==-1) throw 1.0; //double
}
catch(...){
cout<<"Caught an exception"<<endl;
}}
void main(){
cout<<"Testing 1 catch for all exception..."<<endl;
cout<<"x==1"<<endl;
test(1);
cout<<"x==0"<<endl;
test(0);
cout<<"x==-1"<<endl;
test(-1);
cout<<"x==-2"<<endl;
test(-2);
getch();
}

No comments:

Post a Comment