异常学习
一、异常处理之try。。。catch
- 格式
try {
可能出现异常的代码;
}catch(异常类名 变量名){
异常处理的代码;
}
- 例子
int []arr = {1,2,3};
try {
System.out.println(arr[3]);
}catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
System.out.println("数组索引出错");
}
二、异常处理常用函数
- 函数都来自Throwable的成员方法
- public string getMessage():返回错误信息
- public string toString():返回异常简短描述
- public void printStackTrace():把错误信息输出
三、异常处理之throws
- 概念将异常抛出给上一级函数处理,若没有上一级函数处理则交给jvm处理
- 格式:
public static void methods()throws ArrayIndexOutOfBoundsException{
int[] arr={1,2,3};
System.out.println(arr[3]);
}
try {
methods();
}catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
四、自定义异常
- 定义格式
public class 异常名 extends Exception{
无参构造
带参构造
}
- 使用格式
public class 函数名(){
方法名 throws 异常名{
throw new 异常对象;
}
}
- 例子:
public class MyException extends Exception{
public MyException() {
}
public MyException(String message) {
super(message);
}
}
public static void methods()throws MyException{
throw new MyException("xx原因出错");
}
try {
methods();
}catch (MyException e){
e.printStackTrace();
}