异常解析
来源:互联网 发布:广州房地产交易数据 编辑:程序博客网 时间:2024/05/22 08:07
异常:程序在运行时出现的不正常情况
异常的由来:程序在运行时出现的不正常情况也被看成了对象,提取属性和行为进行描述( 比如异常信息,异常名称,异常发生的位置),从而形成了各种异常类
Throwable是Error和Exception的父类
Throwable
—Error :运行时出现的严重问题,不用写相关的处理代码
—Exception :不严重的问题,通常需要进行处理
下面一个简单的数组越界异常
class Demo7 { public static void main(String[] args) { int[] arr = new int[3]; /* 当发生下标越界异常时,因为这种下标越界异常在java内部已经定义好了,所以系统会自动创建 该异常类对象,因为main函数处理不了这种异常抛给了JVM,JVM默认的处理方式就是调用该异常类对象 的printStackTrace()方法,打印出异常类名称,异常信息,异常发生的位置,然后程序中断 */ System.out.println(arr[3]); //throw new ArrayIndexOutOfBoundsException()---JVM System.out.println("over"); }}
使用throws声明可能发生异常,那么调用者必须处理,
处理方式有两种
1:使用try{}catch(异常类 e){}处理
2:继续使用throws声明可能发生异常
class MyMath{ public int div(int a,int b) { return a/b; //throw new ArithmeticException() }}class Demo9 { public static void main(String[] args) { MyMath myMath = new MyMath(); try { int result = myMath.div(3,0); //new ArithmeticException() System.out.println("result="+result); } catch(Exception e)//Exception e = new ArithmeticException() { //System.out.println("除数为0了"); //System.out.println(e.getMessage());//异常信息 //System.out.println(e.toString());//异常名称:异常信息 e.printStackTrace();//异常名称:异常信息 异常发生的位置 } System.out.println("go on"); }}
class MyMath{ public int div(int a,int b)throws ArithmeticException,ArrayIndexOutOfBoundsException { int[] arr = new int[4]; System.out.println(arr[4]);// throw new ArrayIndexOutOfBoundsException();//如果这里抛异常了那么下面就不运行了 return a/b;//在上面不抛异常的情况下,若b为0那么抛异常 }}class Demo11 { public static void main(String[] args)//多重异常--子类异常要写在父类异常的上边儿 { MyMath myMath = new MyMath(); try { int result = myMath.div(3,0); //new ArrayIndexOutOfBoundsException() System.out.println("result="+result); } catch (ArithmeticException e)//Exception e= new ArrayIndexOutOfBoundsException(); { System.out.println("除数为0了"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("下标越界了"); } }}
0 0
- 异常解析
- 异常解析
- 一种异常解析-HeapValidate异常
- XML 解析异常
- java 中的异常解析
- C# 异常原因解析
- JAVA常见异常解析
- ARM异常处理解析
- el函数解析异常
- Java中的异常解析
- java 异常信息解析
- JAVA常见异常解析
- JAVA常见异常解析
- spring xml解析异常
- java异常解析
- JAVA异常解析
- sax解析xml异常
- json解析异常
- MySql update inner join!MySql跨表更新 多表update sql语句?如何将select出来的部分数据update到另一个表里面?
- C++ hdoj 2018 母牛的故事
- 汇总先
- 设计模式-装饰模式
- KMP详解
- 异常解析
- 自定义actionbar的xml(待补充)
- 基于Spring+SpringMVC+Mybatis的秒杀系统之web层(3)
- hdu-4734-数位Dp
- jQuery、zepto选择同时包含两个class的元素
- sublime 3
- 快速解决ThinkPHP 项目中使用原生PHP导致的SQL注入问题
- 柱状图的实现
- JSON学习笔记