首页 > 开发 > Java > 正文

java 异常详解及应用实例

2024-07-13 10:03:13
字体:
来源:转载
供稿:网友

java/169072.html">javascript/41921.html">java  异常

 异常的使用实例(异常分类:Error(是由JVM调用系统底层发生的,只能修改代码) 和 Exception(是JVM发生的,可以进行针对性处理))

 1.如果一个方法内可能出现异常,那么可以将异常通过throw的方式new 出相应的异常类,并在方法上   声明throws可能抛出的异常类抛给调用者,调用者可以进行异常捕获,或者继续抛出异常由 上层调用者继续处理,    如果整个过程都没有将异常进行任何处理,那么将由JVM虚拟机进行默认的处理 

2.调用者可以对异常进行try()catch(){}的异常处理, 也可以继续在方法后面throws该异常,catch代码块中    如果不处理也可以进行throw该异常

 3.运行时异常RuntimeException可以不进行显式的异常声明

 4.如果父类中的方法抛出了异常,如果子类对方法进行重写后也抛出异常,那么该异常必须不能大于父类的异常类, 如果父类中方法没有抛出异常,而子类中覆盖的方法却抛出了异常,那么此时只能进行try catch来捕获此异常,但是也可以将此异常在catch代码块中throw  new RuntimeExcetion()进行抛出,这样方法不用进行throws声明  

 5.很多时候异常并不需要调用者进行处理,调用者不一定具有处理能力

 6.异常应该包装成上层调用者可以识别的异常类型,面向不同的调用者,报告不同的异常信息,否者调用者不知道如何处理该异常

    在开发中这点十分重要

  7.finally代码块中常常进行资源的释放及关闭操作,对于打开的资源应该进行反方向的关闭操作,因为资源可能存在依赖性

  8.如果不进行声明异常,那么目的是不让调用者进行处理,让调用者的程序停止,这样必须修改错误代码

public class ExceptionDemo { public static void main(String[] args) { //OutOfMemoryError内存溢出错误, int[] i = new int[1024*1024*1024]; System.out.println(i[1]);  //ArrayIndexOutOfBoundsException索引越界异常 int[] s = new int[2]; System.out.println(s[2]);   Calc calc = new Calc();  //假如我们在这里捕获异常 try {  calc.run(4, 0);  calc.run(4, -1); } catch (NegativeException e) {//必须先抛出异常的自定义子类  e.printStackTrace();  System.out.println(e.getMessage());  //throw e;//可以继续将此异常抛出 } catch (ArithmeticException e){//抛出自定义异常类的父类  e.printStackTrace();  System.out.println(e.getMessage());  //throw e; } finally {  System.out.println("finally肯定会执行到"); } //如果上面进行了异常捕获,那么代码可以继续执行,否者代码不能继续执行 System.out.println("可以执行到!");  try {  calc.run(4, -1);   } catch (NegativeException e) {  e.printStackTrace();  System.out.println(e.getMessage());  return; } finally {  System.out.println("肯定会执行的"); } System.out.println("执行不到了");//执行不到此行代码  }}/** * 自定义异常 */class NegativeException extends ArithmeticException{ public NegativeException() { } public NegativeException(String msg) { super(msg); }}interface AA{ public abstract void method();}class Calc implements AA{ //ArithmeticException其实为运行时异常(RuntimeException),即使不进行throws声明,也可以通过编译 public int run(int m,int n)throws ArithmeticException,NegativeException{ if(n==0){  throw new ArithmeticException("除数不能为0"); }else if(n<0){  throw new NegativeException("除数不能为负数"); } int s = m/n; return s ; } @Override public void method() { try {  int p = 4/0; } catch (ArithmeticException e) {  e.printStackTrace();  throw new RuntimeException();//将异常继续抛出为运行时异常 } }}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表