异常
异常的概述

JVM的默认处理方案

异常处理
- 异常处理之try...catch...
- 格式

package Error; public class ExceptionDemo1 { public static void main(String[] args) { System.out.println("开始"); method(); System.out.println("结束"); } public static void method(){ try { int[] arr = {1, 2, 3}; System.out.println(arr[3]);//new ArrayIndexOutOfBoundsException() }catch (ArrayIndexOutOfBoundsException e ){ // System.out.println("你访问的数组的索引不存在"); e.printStackTrace(); } } }
Throwable的成员方法

package Error; public class ExceptionDemo1 { public static void main(String[] args) { System.out.println("开始"); method(); System.out.println("结束"); } public static void method(){ try { int[] arr = {1, 2, 3}; System.out.println(arr[3]);//new ArrayIndexOutOfBoundsException() }catch (ArrayIndexOutOfBoundsException e ){ // System.out.println("你访问的数组的索引不存在"); // e.printStackTrace(); // //getMessage() 返回此throwvble 的详细消息字符串 // System.out.println(e.getMessage()); //toString(),返回此可抛出的简短描述 System.out.println(e.toString()); //java.lang.ArrayIndexOutOfBoundsException: 3 //printStackTrace 把异常的错误信息输出在控制台 e.printStackTrace(); } } }
编译时异常和运行时异常的区别

异常处理之throws


自定义异常

package Error; public class ScoreException extends Exception{ public ScoreException(){} public ScoreException(String message){ super(message); } }
package Error; public class Teacher { public void checkScore(int score) throws ScoreException{ if (score<0 || score>100){ throw new ScoreException("你给的分数有误,分数应该在0到100之间"); }else { System.out.println("分数正常"); } } }



浙公网安备 33010602011771号