问:怎么把一本书读成一张薄纸?
答:坚持、专注、不断重复。
1、什么是异常?
答:用于一些无法避免,但是又可以预料的错误,如运行环境问题造成程序异常中止、内存不足、打开文件不存在、文件读写不成功、执行了0以外的操作等等。
2、异常处理过程是什么?
典型实现是像标准错误流(cerr)发送消息(abnormal program termination),然后异常终止。它还返回一个随实现而异的值,告诉操作系统(如果程序是由另一个程序调用,则告诉父进程),处理失败。
异常简单实现。
c/c++常规异常处理
int tmpA = 2021, tmpB = 0;
if (tmpB == 0)
{
std::abort(); // #include <cstdlib>
exit(1);
//#define EXIT_SUCCESS 0
//#define EXIT_FAILURE 1
// 不用异常结束,也可以用返回码代替
return -1;
}
double result = tmpA / tmpB;
c++异常机制
// c++异常机制
try
{
运行代码...
if(异常条件)
{
throw 自定义标记;
}
}
catch(自定义标记的类型)
{
异常处理代码...
}
c++异常机制,简单代码实现。
#include <iostream>
//异常 abnormal
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
double division(int a, int b) {
if (b == 0) {
throw 1;
}
if (b == 1) {
throw false;
}
return (a / b);
}
int main(int argc, char* argv[])
{
int x = 1, y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}
catch (int) { //catch捕获的是throw的内容
cerr << "错误:除数为0" << endl;
}
catch (bool) {
cerr << "触发了假的错误:除数为1" << endl;
}
return 0;
}
类对象作为异常捕获
#define _CRT_SECURE_NO_WARNINGS
//异常 abnormal
#include <iostream>
#include <string.h>
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
#define WHERE_SIZE 32
#define WHAT_SIZE 32
class Abnormal
{
public:
char m_szWhere[WHERE_SIZE];
char m_szWhat[WHAT_SIZE];
};
Abnormal abnormal;
double division(int a, int b) {
if (b == 2)
{
strcpy(abnormal.m_szWhere, "division");
strcpy(abnormal.m_szWhat, "i see a 2...");
throw abnormal;
}
return (a / b);
}
int main(int argc, char* argv[])
{
int x = 1, y = 2;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}
catch (Abnormal &abnormal) // Abnormal
{
cerr << abnormal.m_szWhere << "发生了错误,错误信息为:" << abnormal.m_szWhat;
}
return 0;
}
//拓展一:异常中怎么使用inline内联函数
//拓展二:异常可以继承派生
python中的异常机制:Python是面向对象语言,所以程序抛出的异常也是类。
异常类传送门
def func():
try:
1/0
except: #捕获的所有异常都交给它处理
print("can't be Zoro.")
func()
def func():
try:
1/1
except:
print("can't be Zoro.")
else:
print("safety.")
func()
def func():
try:
1/1
except:
print("can't be Zoro.")
else:
print("safety.")
finally:
print("aways call me.")
func()
打印结果:
can't be Zoro.
>>>
safety.
>>>
safety.
aways call me.
>>>
js定义的七种错误类型:
- SyntaxError:语法错误
- ReferenceError:引用错误(引用不存在的变量时发生 或 将变量赋值给一个无法赋值的对象时发生)
- RangeError:超出范围
- TypeError:类型错
- URLError:URL错误
- InternalError:内部错误
- EvalError:eval错误
js异常处理机制
<script>
try{
tmpA=1;
tmpB=0;
var tmp = tmpA/tmpB;
var tmp2 = 1/0;
console.log(tmp);
console.log(tmp2);
console.log(b);
console.log("以下代码不执行");
}catch(error){
if(error instanceof ReferenceError){
console.log(error);
}
}
finally
{
console.log("不管正确与否,都执行");
}
</script>
输出结果:
Infinity
VM133:8 Infinity
VM133:14 ReferenceError: b is not defined
at <anonymous>:9:15
at submitTryit (try.php?filename=tryhtml_headers:172)
at HTMLButtonElement.onclick (try.php?filename=tryhtml_headers:44)
VM133:19 不管正确与否,都执行