Try Catch
/*
public String getMessage()返回可输出的简短描述
public String toString()返回异常的详细信息
public void printStackTrace()把异常信息输出到控制台
*/
public class Test {
public static void main(String[] args) {
try{
int[] a={1,2,3};
System.out.println(a[5]);//数据下标越界,产生错误
}catch (Exception e){
System.out.println(e.getMessage());//在控制台打印出错误信息
e.printStackTrace();
}
}
}
Throws与throw
/*
`throws Exception 无论后面代码有没有问题,他都会抛,抛给调用者。
throw 写在方法里的,表示肯定抛出
*/
public class Test {
public static void main(String[] args) {
try{
show();
}catch (Exception e){
e.printStackTrace();
}
}
public static void show() throws Exception {//抛出异常
System.out.println(5/1);
}
}
public class Student {
public int age;
public int getAge() {
return age;
}
public void setAge(int age) throws Exception{//抛出
if(age<=120&&age>=1){
this.age = age;
}else {
throw new StudentAgeOut("年龄异常");//自定义异常反馈
}
}
}
自定义错误异常显示
public class Test {;
public static void main(String[] args) throws Exception {//将错误抛给控制台进行显示
Student student=new Student();
student.setAge(1200);
}
}