1.所谓异常就是指程序在运行时出现错误时通知调用者的一种机制。
2.异常举例
①除以“0”
system.out.println(10/0);
//执行结果
Exception in thread "main" java.lang.ArithmeticException : / by zero
②数组下标越界
int[] arr = {11,2,3};
system.out.println(arr[100]);
//执行结果
Exception in thread "main" java.lang.ArrayIndexoutofBoundsException : 100
③访问 null 对象
public class Test {
public int num = 100;
public static void main(string[] args){
Test t = null;
sysout.out.println(t.num);
}
}
//执行结果
Exception in thread "main" java.lang.nullpointerException
1.捕获异常
基本语法:
try{
//又可能出现异常的语句;
}[catch (//异常类型 异常对象) {
}...]
[finally {
//异常出口
}]
说明:
int[1,2,3];
system.out.println("before");
system.out.println(arr[100]);
system.out.println("after");
//执行结果
Exception in thread "main" java.lang.ArrayIndexoutofBoundsException : 100
一旦出现异常,程序就终止了 .after 没有正确输出。
②使用 try catch 后的程序执行过程
int[1,2,3];
try{
system.out.println("before");
system.out.println(arr[100]);
system.out.println("after");
}catch(ArrayIndexoutofBoundsException e) {
//打印出现异常的调用栈
e.printStackTrace();
}
system.out.println("after try catch");
//执行结果
before
java.lang.ArrayIndexoutofBoundsException : 100
at demo02.Test.main(Test.java: 10)
after try catch
一旦 try 中出现异常,那么 try 代码块中的程序就不会继续执行,而是交给 catch 中的代码块来执行 .catch 执行完毕会继续往下执行。
public static void main(string[] args){
system.out.println(readFile());
}
public static String readFile(){
//尝试打开文件,并读其中一行
File file = new file ("d : /test.txt");
//使用文件对象构造 Scanner 对象
Scanner sc = new Scanner (file);
return sc.nextLine();
}
//编译出错
Error: (13,22) java : 未报告的异常错误 java.io.FileNotFoundException; 必须对其进行捕获或声明以便抛出。
显式处理方法:
①使用 try catch
public static void main(string[] args){
system.out.println(readFile());
}
public static String readFile(){
File file = new file ("d : /test.txt");
Scanner sc = null;
try{
sc = new Scanner(file);
}catch(FileNotFoundException e){
e.printStackTrace();
}
return sc.nextLine();
}
②在方法上加上异常说明,相当于将处理动作交给上级调用者
public static void main(string[] args){
try{
system.out.println(readFile());
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
public static String readFile(){
File file = new file ("d : /test.txt");
Scanner sc = new Scanner (file);
return sc.nextLine();
}
扩展
Java中还存在自定义异常,自定义异常通常会继承自 Exception 或者 RuntimeException;
继承自Exception的异常默认是受查异常;
继承自RuntimeException的异常默认是非受查异常。
以上为我对Java异常的一些浅显的总结。仅供大家参考,有错误请及时联系更改。欢迎大家提出建议。
才学疏浅,总结的不是很全面,还望见谅。