什么是异常?
异常既有由用户错误引起的,也有由程序错误引起的,也有由物理错误引起的。
异常处理关键字:
try、catch、finally、throw、throws
注意事项:
1、失误不是异常,而是脱离程序员控制的问题。
2、所有异常类都是从java.lang.Exception类继承的子类。
3、异常类有两个主要子类: IOException类和RuntimeException类。
4、Java有很多内置异常类。
(视频教程推荐: java视频)
语法: try{
//要侦听的代码块
}
catch (异常类型异常名称/e ) {
处理//try捕获到的错误的代码块
throw异常名称/e; //thorw表示抛出异常
throw new异常类型(“自定义”
}
法利{
//finally模块内的语句无论出现异常还是不出现异常都将被执行
}
修饰符方法名称() throws异常类型)。
//throws只用于声明异常,是否抛出由方法调用方决定
//代码块
}
示例代码: (try和catch和finally )公共类扩展测试{
publicstaticvoidmain (string [ ] args ) {
scanner input=new scanner (system.in );
拦截try{ //代码块
int a=input.nextInt (;
int b=input.nextInt (;
double sum=a/b;
system.out.println(sum;
}
catch(inputmismatchexceptione )
System.out.println ('只能输入数字);
}
缓存(arithmeticexceptione ) {
System.out.println ('分母不能为0 );
}
catch(exceptione ) { //Exception是所有异常的父类
System.out.println ('发生其他异常);
}
finally//无论有无异常,finally都一定会被执行
System.out.println (“程序结束”);
}
}
}
代码示例: (throw关键字) import Java.util.inputmismatchexception;
import java.util.Scanner;
公共类扩展测试{
publicstaticvoidmain (string [ ] args ) {
scanner input=new scanner (system.in );
拦截try{ //代码块
int a=input.nextInt (;
int b=input.nextInt (;
double sum=a/b;
system.out.println(sum;
}
catch (inputmismatchexceptione (//catch ) )。
System.out.println ('只能输入数字);
throw e; 扔出catch捕捉到的异常
//thrownewinputmismatchexception (; 同上
}
缓存(arithmeticexceptione ) {
System.out.println ('分母不能为0 );
throw new ArithmeticException ('分母为0时抛出异常); 抛出ArithmeticException异常
}
catch(exceptione ) { //Exception是所有异常的父类
System.out.println ('发生其他异常);
}
finally//无论有无异常,finally都一定会被执行
System.out.println (“程序结束”);
}
}
}
示例代码: (throws )公共类throws
int a=1;
int b=0;
公共void out (throwsarithmeticexception ) /声明可能抛出的异常可以存在多个,用逗号分隔
拦截try{ //代码块
int sum=a/b;
system.out.println(sum;
}
缓存(arithmeticexceptione ) {
System.out.println ('分母不能为0 );
}
finally//无论有无异常,finally都一定会被执行
System.out.println (“程序结束”);
}
}
publicstaticvoidmain (string [ ] args ) {
Throws t=new Throws (;
t.out (; 调用//方法
throw new ArithmeticException ('分母为0时抛出异常); //调用的方法决定是否抛出异常
/*
*第二种慢速方法
*/
//arithmeticexceptiona=newarithmeticexception (“分母为0,抛出异常”);
//throw a;
}
}