异常
因为java在开发程序的过程中,如果遇见异常 默认会
1.输出异常信息,给出异常的位置
2.终止程序的运行
所以我们需要自己手动去捕获异常
捕获异常的两种方式
-
try...catch...
-
throw:谁调用谁来处理
throwable的常用方法
package com.FreeGiao.ExceptionDemo; public class ExceptionDemo01 { public static void main(String[] args) { System.out.println("开始"); method(); System.out.println("结束"); } public static void method(){ try{ int[] arr = {1,2,3,4,6,7}; System.out.println(arr[8]);// new ArrayIndexOutOfBoundsException(); }catch (ArrayIndexOutOfBoundsException a){ //Throwable的成员方法 // a.printStackTrace();//最全面包括 类名,错误原因,错误位置 // System.out.println(a.getMessage());//错误原因 System.out.println(a.toString());//类名+错误原因 } } }
编译时异常&运行时异常
-
运行时异常:可以显示处理或者不处理
-
编译时异常:必须显示处理,否则程序不能运行
自定义异
案例
package com.FreeGiao.ExceptionDemo; public class ScoreException extends Exception { public ScoreException(){ } public ScoreException(String message){ super(message); } } package com.FreeGiao.ExceptionDemo; public class Teacher { public void testScore(int score) throws ScoreException { if (score < 0 || score > 100) { // throw new ScoreException("您输入的分数异常(0<score<100)"); throw new ScoreException(); } else { System.out.println("分数正常"); } } } package com.FreeGiao.ExceptionDemo; import java.util.Scanner; public class TestDemo { public static void main(String[] args) { Scanner ss = new Scanner(System.in); System.out.println("请输入您的成绩:"); int i = ss.nextInt(); Teacher tt = new Teacher(); try { tt.testScore(i); } catch (ScoreException e) { e.printStackTrace(); } } } answer1: 请输入您的成绩: 500 com.FreeGiao.ExceptionDemo.ScoreException at com.FreeGiao.ExceptionDemo.Teacher.testScore(Teacher.java:7) at com.FreeGiao.ExceptionDemo.TestDemo.main(TestDemo.java:13) Process finished with exit code 0 请输入您的成绩: 500 com.FreeGiao.ExceptionDemo.ScoreException: 您输入的分数异常(0<score<100) at com.FreeGiao.ExceptionDemo.Teacher.testScore(Teacher.java:6) at com.FreeGiao.ExceptionDemo.TestDemo.main(TestDemo.java:13)