什么是异常
程序运行的过程中发生的一些不正常事件
异常分类
Throwable
Error 错误
Exception
IOException
RuntimeException 编程错误 可以不用采用异常处理
java的异常通过两种机制来处理
捕获 try-catch-finally
try 监控 catch 处理 finally 总是执行
package com.date; import java.util.InputMismatchException; import java.util.Scanner; public class TryDemo { public static void main(String[] args) { System.out.println("请输入一个数字"); Scanner input=new Scanner(System.in); int a=input.nextInt(); int res=0; try { res=10/a; }catch (Exception e) { System.out.println(e.getMessage()); }finally {//释放资源,比如关闭打开的文件 System.out.println("结果为:"+res); } /*} catch (InputMismatchException e) { System.out.println(e.getMessage()); e.printStackTrace(); }catch (ArithmeticException e) { System.out.println(); }*/ } }
抛出 throw,throws
throw 手动抛出异常(弹出)
throws 声明方法抛出异常
package com.date; public class throwDemo { public static void main(String[] args) { Bar bar=new Bar(); try { bar.enter(15); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } System.out.println("end"); } } class Bar{ public void enter(int age) throws IllegalArgumentException { if(age<19) { throw new IllegalArgumentException("年龄不合格"); }else { System.out.println("欢迎"); } } }
自定义异常
必须从已有的异常类继承
Exception 必须用throws
package com.date; public class zidingyiyichDemo { public static void main(String[] args) { Bar1 bar=new Bar1(); try { bar.enter(18); } catch (AgeLessThanEighteenException e) { System.out.println(e.getMessage()); } System.out.println("end"); } } class AgeLessThanEighteenException extends Exception{ private String message;//描述异常信息 public AgeLessThanEighteenException(String message) { this.message = message; } @Override public String getMessage() { return message; } } class Bar1{ public void enter(int age) throws AgeLessThanEighteenException { if(age<19) { throw new AgeLessThanEighteenException("年龄不合格"); }else { System.out.println("欢迎"); } } }