目录
一、理解异常及异常处理的概念二、掌握Java异常处理机制三、掌握try 、catch 、 finally 处理异常 3.1、try..catch3.2、try..catch..finally四、掌握throw 抛出异常、throws 声明异常 4.1、java中常用的异常4.2、throw..throws五、掌握自定义异常异常就是在程序的运行过程中所发生的不正常的事件,它会中断正在运行的程序。
异常不是错误
程序中关键的位置有异常处理,提高程序的稳定性
Java的异常处理是通过5个关键字来实现的
try:尝试,把有可能发生错误的代码放在其中,必须有
catch:捕获,当发生异常时执行
finally:最终,不管是否有异常都将执行
throw:抛出,引发异常
throws:抛出多个,声明方法将产生某些异常
异常处理:
package com.zhangguo.chapter6.d1; import java.util.Scanner; public class Exception1 { public static void main(String[] args) { try { Scanner input = new Scanner(System.in); int i = Integer.parseInt(input.next()); System.out.println("您输入的是:" + i); } catch (Exception exp) { System.out.println("发生异常了:" + exp.getMessage()); } System.out.println("程序结束了"); } }结果:
finally在任何情况下都将执行,正常时会执行,不正常也会执行
package com.zhangguo.chapter6.d1; import java.util.Scanner; public class Exception1 { public static void main(String[] args) { try { Scanner input = new Scanner(System.in); int i = Integer.parseInt(input.next()); System.out.println("您输入的是:" + i); } catch (Exception exp) { System.out.println("发生异常了:" + exp.getMessage()); }finally { System.out.println("输入结束"); } System.out.println("程序结束了"); } }结果:
1您输入的是:1输入结束程序结束了
如果用户输入是的xyz
运行结果:
public class ArithmeticException extends RuntimeException { private static final long serialVersionUID = 2256477558314496007L; /** * Constructs an {@code ArithmeticException} with no detail * message. */ public ArithmeticException() { super(); } /** * Constructs an {@code ArithmeticException} with the specified * detail message. * * @param s the detail message. */ public ArithmeticException(String s) { super(s); } }
转载于:https://www.cnblogs.com/zzqwe/p/8516486.html