这里写目录标题
1.异常:
I. 程序在运行过程中出现的特殊情况。
II. 异常处理的必要性:任何程序都可能存在大量的未知问题、错误;如果不对这些问题进行正确处理,则可能导致程序的中断,造成不必要的损失。
2. 异常的分类:
I-Throwable:可抛出的,一切错误或异常的父类。位于java.lang包中。
|-Error:JVM、硬件、执行逻辑错误,不能手动处理。
|-Exception:程序在运行和配置过程中产生的问题,可处理。
|-RuntimeException:运行时异常,可处理,可不处理。
|-CheckedException:受查异常,必须处理。
3. 异常的产生:
I. 自动抛出异常:当程序在运行时遇到不符合规范的代码或结果时,会产生异常。
II. 手动抛出异常:throw new 异常类型(“实际参数”);
III. 一旦产生异常结果:相当于执行return语句,导致程序因异常而终止。
4. 异常的传递:
I. 按照方法的调用链反向传递,如果最终都没有处理异常,最终交由我们的JVM进行默认异常处理(打印堆栈跟踪信息)
II. 受查异常:throws 声明异常,声明位置:修饰在方法参数列表的后端。
III. 运行时异常:因其可处理,可不处理,无需声明。
5. 异常的处理:
I. try{
//可能出现异常的代码
}catch(Exception e){
//捕获异常后,对异常处理的相关代码。处理方案:1、自定义2、printStackTrace();3、getMessage();
}finally{
//无论是否出现异常,都需要执行的代码。 常用于释放资源.
}
II. 常见异常处理结构
(1) try{ }catch(){}
(2) try{}catch(){}catch(){}
(3) try{}catch(){}finally{}
(4) Try{}catch(){}catch(){}finally{}
(5) try{}finally{}
注意:多重catch下,遵循从子到父的顺序,父类异常在最后捕获
6. 自定义异常:
I. 继承Exception(受查异常)或Exception的子类。常用RuntimeException.(运行时异常)
II. 必要提供的内容
(1) .无参构造方法
(2) String message参数的构造方法。定义异常原因信息
7. 异常方法覆盖:
I. 方法名、参数列表、返回值类型必须和父类相同
II. 子类的访问修饰符和父类相同或比父类更宽泛
III. 子类中的方法,不能抛出比父类更宽泛的异常。
try {
System.out.println("请输入一个被除数");
int num1 = sc.nextInt();
System.out.println("请输入一个除数");
int num2 = sc.nextInt();
} catch (ArithmeticException e) {
System.out.println("除数不能为0");//自定义处理
e.printStackTrace(); //打印堆栈跟踪信息
e.getMessage(); //获取异常原因的message
}catch (InputMismatchException e) {
System.out.println("输入参数错误");
}finally {
System.out.println("解决异常");
}
public void setAge(int age) throws Exception {
if(age>0 && age < 125) {
this.age = age;
}else{
Exception re = new Exception(); //运行时异常可以不用抛出
throw re;
}
}
8. 举个例子:
class TestException{
public static void main(Stringargs[]){
System.out.println(“main1”);
ma(n);
System.out.println(“main2”);
}
public static void ma(int n){
try{
System.out.println(“ma1”);
mb(n);
System.out.println(“ma2”);
}catch(EOFExceptione){
System.out.println(“CatchEOFException”);
}catch(IOExceptione){
System.out.println(“CatchIOException”);
}catch(SQLExceptione){
System.out.println(“CatchSQLException”);
}catch(Exceptione{
System.out.println(“CatchException”);
}finally{
System.out.println(“Infinally”);
}
}
public static void mb(int n) throws Exception {
System.out.println(“mb1”);
if(n==1)throw newEOFException();
if(n==2)throw newFileNotFoundException();
if(n==3)throw newSQLException();
if(n==4)throw newNullPointerException();
System.out.println(“mb2”)
}
}
当 n = 1时,输出
main1
ma1
mb1
Catch EOFException
In finally
main2
注意:try代码块中遇到异常被捕获后,try代码块剩下还未执行的代码会立即停止运行,但是try-catch结构后的代码依旧可以运行。throw new Exception()后的代码也是不会执行的。
public static void main(String[] args) {
System.out.println(ma(1));
}
public static int ma(int b) {
//读入b
try {
m();
return 100;
} catch (Exception e) {
System.out.println("Exception");
}
System.out.println("wojinranhaizai");
return b;
}
Java中使用try…catch来处理异常,今天在debug一段用try…catch处理的代码段,调试时throws Exception, 感觉抛出的异常有问题,但是又很难对出现问题的地方进行识别定位,把进行异常的处理的代码不进行异常处理,再调试的时候很容易定位出出现问题的代码语句
Warning:
try…catch包括的代码不应过多,否则难定位出问题