Throwable的成员方法
public void printStackTrace() 把异常的错误信息输出在控制台
public String toString() 返回此抛出的简短描述
public String getMessage() 返回throwable的详细消息字符串
try...catch
格式:try{可能出现异常的代码;}catch(变量名 异常名) {异常的处理代码;}
package 异常;
public class Yichang {
public static void main(String[] args) {
try {
int[] arr= {1,2,3};
System.out.println(arr[3]);}
/*Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at 异常.Yichang.main(Yichang.java:9)*/
catch(ArrayIndexOutOfBoundsException a) {
System.out.println("存在错误!");
//public void printStackTrace() 把异常的错误信息输出在控制台
//public String toString() 返回此抛出的简短描述
//public String getMessage() 返回throwable的详细消息字符串
//a.printStackTrace();
/*存在错误!
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at 异常.Yichang.main(Yichang.java:9)*/
System.out.println(a.toString());
//java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
System.out.println(a.getMessage());
//Index 3 out of bounds for length 3
}
}
}
throws
格式:throws 异常类名;【跟在方法的括号后面】
public static void method() throws ArrayIndexOutOfBoundsException{
int[] arr= {1,2,3};
System.out.println(arr[3]);
}
throws | throw |
---|---|
用在方法声明后面,跟的是异常类名 | 用在方法体内,跟的是异常对象名 |
表示抛出异常,由该方法调用者来处理 | 表示抛出异常,由方法体内的语句来处理 |
表示抛出异常的一种可能性,并不一定会发生这些异常 | 执行throw一定抛出了某种异常 |
自定义异常
继承自Exception类
格式:
public class 异常类名 extends Exception{
无参构造
带参构造
}
public class Zidingyi extends Exception {
/*
* 报错: serializable 类 Zidingyi 未声明类型为 long 的静态终态 serialVersionUID 字段
*/
private static final long serialVersionUID = -5068192539448251924L;
public Zidingyi() {}
public Zidingyi(String message) {
super(message);
}
}
举例(应用自定义异常+try...catch+throws+throw)
package 异常;
public class Zidingyi extends Exception {
/*
* 报错: serializable 类 Zidingyi 未声明类型为 long 的静态终态 serialVersionUID 字段
*/
private static final long serialVersionUID = -5068192539448251924L;
public Zidingyi() {}
public Zidingyi(String message) {
super(message);
}
public static void check(int score) throws Zidingyi{
if(score<0||score>100) {
throw new Zidingyi();
}else {System.out.println("分数正常");}
}
public static void main(String[] args) {
try {
check(-111);
} catch (Zidingyi e) {
e.printStackTrace();
}
/*try {
check(1);
} catch (Zidingyi e) {
e.printStackTrace();
}*/
}
}