一、异常定义:指的是程序在执行过程中,出现的非正常情况,如果不处理最终会导致JVM的非正常停止。
注意:异常指的并不是语法错误。语法错了,编译不通过,不会产生字节码文件,根本不能运行。
二、异常体系图
三、常见的异常
Error
1、堆溢出: OutOfMemoryError
2、栈溢出: StackOverflowError
Exception
1、算数异常(ArithmeticException) 在除数为0时会出现 2、数组下标越界异常(ArrayIndexOutOfException) 当数组索引非法时会出现 3、强制类型转换异常(ClassCastException) 转换的两个类型不匹配 4、空指针异常(NullPointerException) 在调用对象时发现对象为NULL 5、类型转换错误(NumberFormatException) 转换的内容与转换类型不匹配 6、字符串索引越界(StringIndexOutOfBoundsException) 调用字符串时索引非法
四、对异常的处理
Java的异常处理是通过5个关键字来实现的:try、catch、 finally、throw、throws
package Exception; public class Exeption_Over { /* Exception:出现的一般问题,可以使用java中的异常机制处理的 -RuntimeException:运行时异常 -刚才那六种都是运行时异常 -:非运行时异常 在写代码的时候就要根据不同的情况设定好处理程序 运行程序之后如果出现问题,就执行异常处理程序,如果运行是没有出现问题 那么就不需要执行异常处理程序了 关键字: try{ } catch{ //catch可以多写几个 } finaly{ } */ public static void main(String[] args) { /* try{ String s=null; int a=10; int b=0; int c=a/b; }catch (ArithmeticException a){ a.printStackTrace(); String str=null; System.out.println("除数不能为零:"+a.getMessage()); }catch (NullPointerException n){ n.printStackTrace(); }finally { System.out.println("空指针异常");//多次输出”空指针异常的时候可以直接写在最后finally之中 }*/ test(); } public static int test(){ try{ int a=10; int b=0; int c=a/b; }catch(ArithmeticException a){ return -1; }finally { System.out.println("算数错误"); } return 0;//无论如何都会走一次finally }