C++提供关键字throw,它可以在任意位置抛出异常,其中throw的操作数可以使任意的表达式,表达式的类型,决定抛出异常的类型。
cin >> a;cin >> b;if(b == 0){throw"error";}else{ c = a/b;}
try、catch、throw三个关键字的使用方法,例子:
#include<iostream>usingnamespacestd;doubledivision(int a, int b){if( b == 0 ) {throw"Division by zero condition!"; }return (a/b);}intmain(){int x = 50;int y = 0;double z = 0;try { z = division(x, y);cout << z << endl; }catch (constchar* msg) {cerr << msg << endl; }return0;}
C++提供了一系列标准的异常,需包含头文件#include <exception>