实际工做中,遇到的状况不多是很是完美的。好比:你写的某个模块,用户输入不必定符合你的要求。你的程序要打开某个文件,这个文件可能不存在或者文件格式不对,你要读取数据库的数据,数据多是空的等。咱们的程序再跑着,内存或硬盘可能满了。等等...java
软件程序在运行过程当中,很是可能遇到刚刚提到的这些异常问题,咱们叫异常,英文是:Exception,意思是例外。这些例外状况,或者叫异常,怎么让咱们写的程序作出合理的处理,而不至于程序崩溃程序员
异常指程序运行中出现的不期而至的各类情况,如:文件找不到,网络链接失败,非法参数等数据库
异常发生在程序运行期间,它影响了正常的程序执行流程编程
要理解Java异常处理是如何工做的,你须要掌握如下三种类型的异常:数组
Java把异常看成对象来处理,并定义一个基类 java.lang.Throwable 做为全部异常的超类网络
在Java API中已经定义了许多异常类,这些异常类分为两大类,错误Error和异常Exception框架
Erroride
Exceptionthis
在Exception分支中有一个重要的子类RuntimeException (运行时异常)spa
ArrayIndexOutOfBoundsException (数组下标越界)
NullPointerException (空指针异常)
ArithmeticException (算术异常)
MissingResourceException (丢失资源)
ClassNotFoundException (找不到类)
.... 这些异常是不检查异常,程序中能够选择捕获处理,也能够不处理
这些异常通常是由程序逻辑错误引发的, 程序应该从逻辑角度尽量避免这类异常的发生
Error和Exception的区别:
抛出异常
捕获异常
异常处理五个关键字
public class Demo01 { public static void main(String[] args) { int a = 1; int b = 0; // System.out.println(a/b);//java.lang.ArithmeticException: / by zero try{ //try监控区 System.out.println(a/b); }catch(ArithmeticException e){ //捕获异常 System.out.println("程序出现异常,变量b不能为0"); }finally{ //处理善后工做 System.out.println("finally"); } /* try catch 必需要有 finally 能够不要,假设IO,资源等关闭操做 */ } } public class Demo02 { public static void main(String[] args) { try{ new Demo02().a(); }catch(Error e){ System.out.println("Error"); //进入这个,异常只能从小到大的去捕获 }catch (Exception e){ System.out.println("Exception"); }catch (Throwable e){ System.out.println("Throwable"); } finally{ System.out.println("finally"); } } public void a(){b();} public void b(){a();} } public class Demo03 { public static void main(String[] args) { int a = 1; int b = 0; //快捷键 Ctrl + Alt + T try { if(b == 0){ throw new ArithmeticException(); //主动抛出异常 throw 什么都没有作,通常在方法中使用 } System.out.println(a/b); } catch (Exception e) { System.out.println("加入本身的逻辑..."); // System.exit(0);//结束程序 // e.printStackTrace(); }finally { } } //假设这个方法中处理不了这个异常,在方法上抛出异常 public void test(int a, int b) throws ArithmeticException{ if(b == 0){ throw new ArithmeticException(); //主动抛出异常 throw 什么都没有作 } } }
使用Java内置的异常类能够描述在编程时出现的大部分异常状况。除此以外,用户还能够自定义异常。用户自定义异常类,只需继承Exception类便可
在程序中使用自定义异常类,大致可分为如下几个步骤
//自定义异常类 public class MyException extends Exception{ //传递数字 > 10 private int detail; public MyException( int detail) { this.detail = detail; } //toString:异常的打印信息 @Override public String toString() { return "MyException{" + "detail=" + detail + '}'; } } //应用 public class Test { //可能会存在异常的方法 static void test(int num) throws MyException{ System.out.println("传递的参数为:" + num); if(num > 10){ throw new MyException(num); //抛出 } System.out.println("OK"); } public static void main(String[] args) { try { test(11); } catch (MyException e) { //增长一些处理异常的代码块 System.out.println("MyException --> " + e); } } }