异常是指程序在运行时出现错误时通知给调用者的一种机制
java异常体系
- 顶层Throwable派生两个子类,error和Exception;
- Error是指java运行时内部错误和资源耗尽错误,应用程序不抛出此类异常,这种内壁错误一旦出现,告知用户程序终止,不做任何处理
- Exception指的是异常的父类。
- RuntimeException类的所有异常称为非受查异常,所有其他异常称为受查异常
常见的异常
除0
System.out.println(10/0)
Exception in thread “main” java.lang.ArithmeticException: / by zero
数组下标越界
int [] a = {1,2,3,4,5};
System.out.println(a[10]); Exceptioninthread"main"java.lang.ArrayIndexOutOfBoundsException: 10
空指针
class A { public int n =10; } A a = null; System.out.println(a.n);;
Exception in thread “main” java.lang.NullPointerException
异常的用法
try{
可能出现异常的语句
}catch(异常类型 异常对象){
...
}finally{
异常的出口
}
try代码块中放的是可能出现异常的代码
catch代码块放的是可能出现异常后的行为
finally 代码块中的代码会在最后执行
catch、finally可以视情况添加
若catch中有多个异常,若即有子类异常也有父类异常时,必须将父类异常写在子类异常后面
try{
}catch(NullPointerExceprion e)
{
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
异常的处理流程
举个例子
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
try {
System.out.println(10 / a);
} catch (ArithmeticException e) {
e.printStackTrace();
}finally{
System.out.println("finally");
}
}
注意
public static void main(String[] args) {
int a =fun();
System.out.println(a);
}
static int fun(){
try{
return 3;
}catch (Exception e){
e.printStackTrace();
}finally {
return 5;
}
}
大多数人会觉得这个fun函数返回的结果是3,但是finally中的代码块会必须被执行所以返回结果5,一般不建议在finally中添加return语句
- 程序先执行try中的代码
- 若try中代码出现异常,就会结束try中的代码,和catch中的异常类型进行匹配
- 如果找到匹配的异常类型,就会执行catch中的代码;反之,将异常向上传递到上层调用者
- 无论是否有找到匹配的异常类型,finally中的代码都会被执行
- 若上层调用者也没有处理,就继续向上层继续传递
- 若到主方法也没有处理,则会交给jvm来处理,此时程序会异常终止
受查异常的处理方式
//方式一 try/catch包围
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
try {
String s = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
//方式二抛出异常
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String s = reader.readLine();
}
当出现受查异常时必须显示进行处理
1:使用try catch 包裹起来
2:在方法上加上异常说明,将处理动作交给上级调用者。
自定义异常
用户自己实现的异常称为自定义异常,通过继承RuntimeException来实现自定义异常。用户根据自己的业务逻辑进行自定义异常的书写
class MyException extends RuntimeException{
public Exection(String message) {
super(message);
}
}
调用此异常通过 throw new MyException(“提示用户的异常信息”)
举个例子
public class Exection extends RuntimeException{
public Exection(String message) {
super(message);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
if(a<0){
throw new Exection("请输入一个正数");
}
}
}