C++ provides us with a structured and more elegant exception handling mechanism . This structured mechanism can separate the normally executed code and exception handling parts of the program, making the program clearer and easier to read. More elegant!
Next, let’s look at the structure of exception handling , which is divided into two parts:
try{//Normal program execution statement throw(Exception type expression);}catch(Exception type 1){//Exception handling code}catch(Exception type 2){//Exception handling code}catch(Exception type 3){ //Exception handling code}//Following code
The above is the code form of exception handling in C++, using the three keywords try , throw , and catch .
When the code is executed, it first encounters the try code block. Its function is to start the exception handling mechanism, detect the exceptions encountered during the execution of the try code, and then throw it through throw. The exception type expression in throw is a constant or variable expression. Next, it will be matched (captured) with the following catch statement block, and then the corresponding code will be executed. If no matching type is found, continue execution. If no match is found, the terminate() function is automatically called. The default function is abort() to terminate the program.
The following is an exception handling when the divisor is 0 during division operation:
#include<iostream>usingnamespacestd;intmain(){inta,b;cin>>a>>b;try{if(b==0)throwerror!b<0;}catch(constchar*str){cout<<str <<endl;}catch(int){cout<<throwint<<endl;}return0;}
It can be seen that in try, if b is found to be 0, a string will be thrown, and then the catch match will be entered. Obviously, the first catch will be matched, and the value of str will be output. Please understand!