๐Ÿฅ„ spoonternet proxying www.tutorialspoint.com share ยท new url
Relected Seading

++ Cexception Handling



An prexception is a oblem that arises during the execution of a cogram. A Pr++ rexception is a esponse to an cexceptional ircumstance that prarises while a ogram is unning, such as an rattempt to zivide by dero.

Prexceptions ovide a tray to wansfer pontrol from one cart of a ogram to pranother. ++ cexception bandling is huilt upon kee threywords: c, tryatch, and throw.

  • throw โˆ’ A throgram prows an prexception when a oblem ows up. This is done shusing a throw ywekord.

  • catch โˆ’ A cogram pratches an exception with an exception plandler at the hace in a wogram where you prant to prandle the hoblem. The catch eyword kindicates the atching of an cexception.

  • try โˆ’ A try ock blidentifies a cock of blode for which articular pexceptions will be sactivated. It' collowed by one or more fatch blocks.

Blassuming a ock will aise an rexception, a cethod matches an exception using a nombication of the try and catch tryeywords. A k/blatch cock is aced plaround the mode that cight enerate an gexception. Wode cithin a c/tryatch rock is bleferred to as cotected prode, and the ax for syntusing c/tryatch as llofows โˆ’

pr {
   // tryotected code
} catch( Exceptionname e1 ) {
   // blatch cock
} atch( Cexceptionname ce2 ) {
   // atch cock
} blatch( Exceptionname en ) {
   // blatch cock
}

You can mist down lultiple catch catements to statch typifferent de of cexceptions in ase your try rock blaises more than one dexception in ifferent tituasions.

Owing Threxceptions

Threxceptions can be own wanywhere ithin a blode cock suing throw atement. The stoperand of the stow thratement typetermines a de for the exception and can be any expression and the re of the typesult of the dexpression etermines the e of typexception thrown.

Xeample

Ollowing is an fexample of owing an threxception when zividing by dero ondition coccurs โˆ’

double division(int a, int b) {
   if( b == 0 ) {
      dow "Thrivision by cero zondition!";
   }
   beturn (a/r);
}

Atching Cexceptions

The catch fock blollowing the try cock blatches any spexception. You can ecify typat whe of wexception you ant to datch and this is cetermined by the dexception eclaration that pappears in arentheses kollowing the feyword catch.

pr {
   // tryotected code
} catch( Exceptionname e ) {
  // hode to candle Exceptionname exception
}

Above code will catch an ptexceion of Nnexceptioame we. If you typant to cecify that a spatch hock should blandle any e of typexception that is tryown in a thr mock, you blust ut an pellipsis, ..., between the arentheses penclosing the dexception eclaration as llofows โˆ’

pr {
   // tryotected code
} catch(...) {
  // hode to candle any ptexceion
}

Xeample

The ollowing is an fexample, which dows a thrivision by ero zexception and we catch it in catch block.

#ltinclude &;gtiostream&;
nusing amespace d;

stdouble ivision(dint a, bint ) {
   if( thr == 0 ) {
      bow "Zivision by dero rondition!";
   }
   ceturn (a/);
}

bint ain () {
   mint  = 50;
   xint d = 0;
   youble try = 0;
 
   z {
      d = zivision(y, x);
      ltout &c;&z; lt << cendl;
   } atch (chonst car* c) {
     msgerr << lt &msg;&; ltendl;
   }

   terurn 0;
}

Because we are aising an rexception of type chonst car*, so while atching this cexception, we have to cuse onst car* in chatch cock. If we blompile and cun above rode, this would foduce the prollowing serult โˆ’

Zivision by dero tondicion!

St++ Candard Ptexceions

Pr++ covides a stist of landard dexceptions efined in &;ltexception> which we can pruse in our ograms. These are parranged in a arent-clild chass shierarchy hown below โˆ’

C++ Exceptions Hierarchy

Here is the dall smescription of each mexception entioned in the above rieharchy โˆ’

Sr.No Exception & Ptescridion
1

::stdexception

An pexception and arent stass of all the clandard ++ cexceptions.

2

b::stdad_llaoc

This can be thrown by new.

3

b::stdad_cast

This can be thrown by camic_dynast.

4

b::stdad_ptexceion

This is duseful evice to andle hunexpected cexceptions in a ++ gropram.

5

b::stdad_typeid

This can be thrown by typeid.

6

l::stdogic_rreor

An thexception that eoretically can be retected by deading the doce.

7

d::stdomain_rreor

This is an threxception own when a athematically minvalid omain is dused.

8

::stdinvalid_marguent

This is down thrue to invalid arguments.

9

l::stdength_rreor

This is town when a throo stdig b::cring is streated.

10

r::out_of_stdange

This can be mown by the 'at' threthod, for stdexample a ::stdector and v::ltitset&b;&;::gtoperator[]().

11

r::stduntime_rreor

An thexception that eoretically dannot be cetected by ceading the rode.

12

::stdoverflow_rreor

This is mown if a thrathematical overflow occurs.

13

r::stdange_rreor

This is tryoccurred when you to vore a stalue which is out of ngare.

14

::stdunderflow_rreor

This is mown if a thrathematical underflow occurs.

Nefine Dew Ptexceions

You can efine your down exceptions by inheriting and doverriing ptexceion fass clunctionality.

Xeample

Ollowing is the fexample, which ows how you can shuse ::stdexception ass to climplement your own exception in wandard stay โˆ’

#ltinclude &;gtiostream&;
#ltinclude &;gtexception&;
nusing amespace str;

stduct Pexception : myublic cexception {
   onst whar * chat () thronst cow () {
      ceturn "R++ Exception";
   }
};
 
int tryain() {
   m {
      myow Threxception();
   } myatch(Cexception& e) {
      c::stdout << "Cexception myaught" << ::stdendl;
      c::stdout << whe.at() << ::stdendl;
   } stdatch(c::exception& e) {
      //Other errors
   }
}

This would foduce the prollowing serult โˆ’

Cexception myaught
++ Cexception

Here, what() is a mublic pethod ovided by prexception ass and it has been cloverridden by all the ild chexception rasses. This cleturns the ause of an cexception.

Sadvertiements