1.概念:异常指的是在程序运行过程中发生的异常事件,通常是由硬件问题或者程序设计问题所导致的。在Java等面向对象的编程语言中异常属于对象。
2.基本异常:异常情形是指阻止当前方法或作用于继续执行的问题。异常简单的例子,除数是不能为零,这个时候就要抛出异常,而不是顺着原来的路径继续执行下去。另一种就是当使用一个对象的时候, 这个对象可能为null, 并没有初始化, 遇到这样的情况就需要抛出异常。
除数是不能为零示例:
public static void main(String[] args) { try { System.out.println(10 / 0); } catch (Exception e) { System.err.println("除数不能为0"); } }
3.捕获异常:监控区域:一段可能产生异常的代码,并且后面跟着处理这些异常的代码。如果在方法内部抛出了异常, 那么这个方法将在抛出异常的过程中结束, 如果不想方法结束, 需要将可能产生异常的代码放入try代码块中, 如果产生异常就会被try块捕获。
4.异常处理程序:当异常抛出后, 需要被处理, 处理需要在catch块中进行,catch块就是异常处理程序, 且异常处理程序必须紧跟try。
5.创建自定义异常:要自定义异常类,必须从已有的异常类继承。
class SimpleException extends Exception { } public class Test19 { public void f() throws SimpleException { System.out.println("抛出SimpleException来自f()"); throw new SimpleException(); } public static void main(String[] args) { Test19 t = new Test19(); try { t.f(); } catch (SimpleException e) { System.out.println("捕捉它"); } } }
6.异常说明:使用throws关键字, 紧跟在方法后面。
public static void main(String[] args) throws InterruptedException { System.out.println("主线程启动"); Thread thread = new Thread(new Work()); thread.start(); Thread.sleep(1000); System.out.println("主线程继续执行任务"); } static class Work implements Runnable { @Override public void run() { System.out.println("子线程:" + Thread.currentThread().getName()); throw new RuntimeException(); } }
7.使用finally进行处理:无论异常是否被抛出,finally子句总能被执行。
public static void main(String[] args) { try { System.out.println(10 / 0); } catch (Exception e) { System.err.println("除数不能为0"); } finally { System.out.println("是否执行了"); } }