当前位置: 移动技术网 > IT编程>开发语言>Java > JAVA基础--如何通过异常处理错误

JAVA基础--如何通过异常处理错误

2020年06月14日  | 移动技术网IT编程  | 我要评论

jsp基础教程,辞退员工补偿标准,银行定期存款利率

《thinking in java》上对这章的讲解不少,可见重要性,学习和总结一些主要的记录下来。

一、创建自定义异常

package exception; 
 class simpleexception extends exception{}
 
 public class inheritingexception{
  
  public void f() throws simpleexception {
   system.out.println("throw simpleexception from f()");
   throw new simpleexception();
  }
  
  public static void main(string[] args) {
   inheritingexception sed = new inheritingexception();
   try {
    sed.f();
   } catch (simpleexception e) {
    e.printstacktrace();
   }
  }
  
 }

输出:

throw simpleexception from f()
exception.simpleexception
at exception.inheritingexception.f(inheritingexception.java:10)
at exception.inheritingexception.main(inheritingexception.java:19)

  throw与throws的区别与详情

  编译器创建了默认构造器,它将自动调用基类的默认构造器。

  对异常来说,最重要的部分就是类名,其它也没用,可以增加一个带参的构造方法。

  比如nullpointerexception:

 public class nullpointerexception extends runtimeexception {
  private static final long serialversionuid = 5162710183389028792l;
 
  /**
  * constructs a {@code nullpointerexception} with no detail message.
  */
  public nullpointerexception() {
   super();
 }

  /**
  * constructs a {@code nullpointerexception} with the specified
   * detail message.
  *
  * @param s the detail message.
  */
  public nullpointerexception(string s) {
   super(s);
  }
 }

二、捕获异常

  1)try块

    如果在方法内部抛出了异常(或者在方法内部调用的其他方法抛出了异常),这个方法将在抛出异常的过程中结束。

    要是不希望方法就此结束,可以在方法内设置一个特殊的块来捕获异常。

try{
 //exceptions 
}

   2)异常处理程序

    异常处理程序紧跟在try块之后,以关键字catch表示:

try{
 //exceptions 
} catch(type1 id1) {
 //type1 
} catch(type2 id2) {
 //type2
}

    当异常被抛出时,异常处理机制将负责搜寻参数与异常类型相匹配的第一个处理程序。然后进入catch子句执行,此时认为异常得到了处理。

    注意,只有匹配的catch子句才能得到执行,这与switch语句不同。

   3)栈轨迹

    printstacktrace()方法所提供的信息可以通过getstacktrace()方法来直接访问,这个方法将返回一个由栈轨迹中的元素所构成的数组,其中每一个元素都表示

  栈中的一帧。元素0是栈顶元素,并且是调用序列中的最后一个方法调用。数组中最后一个元素和栈底是调用序列中的第一个方法调用。

 public class whocalled {
  static void f() {
   try {
    throw new exception();
   } catch (exception e) {
    for(stacktraceelement ste : e.getstacktrace()) {
     system.out.println("line: " + ste.getlinenumber() + " method: " + ste.getmethodname());
    }
   }
  }
  static void g() {f();}
  static void h() {g();}
  public static void main(string[] args) {f();g();h();}
 }

  程序输出:

line: 5 method: f
line: 14 method: main
line: 5 method: f
line: 12 method: g
line: 14 method: main
line: 5 method: f
line: 12 method: g
line: 13 method: h
line: 14 method: main

三、java标准异常

  throwable这个java类被用来表示任何可以作为异常被抛出的类。

  throwable对象可分为两种类型:

1  error用来表示编译时和系统错误。

2  exception是可以被抛出的基本类型,程序员关心的基类型通常是exception。

四、runtimeexception

if(t == null) {
 throw new nullpointerexception(); 
}

  如果对null引用进行调用,java会自动抛出nullpointerexception异常,所以上述代码是多余的,它属于java的标准运行时检测的一部分:

public class nevercaught {
  static void f() {
   throw new runtimeexception();
  }
  static void g() {f();}
  public static void main(string[] args) {
   g();
  }
 }

输出:

exception in thread "main" java.lang.runtimeexception

at exception.nevercaught.f(nevercaught.java:6)

at exception.nevercaught.g(nevercaught.java:10)

at exception.nevercaught.main(nevercaught.java:14)

  从输出可以发现,runtimeexception是一个特例,对于这种异常类型,编译器不需要异常说明,其输出被报告给了system.err。

  如果runtimeexception没有被捕获而直达main(),那么在程序退出前将调用异常的printstacktrace()方法。

  *注意:

    只能在代码中忽略runtimeexception(及其子类)类型的异常,其它异常类型的处理都是由编译器强制实施的。

  1)常见的五种runtimeexception

nullpointerexception - 空指针引用异常

classcastexception - 类型强制转换异常

illegalargumentexception - 传递非法参数异常

arithmeticexception - 算术运算异常

arraystoreexception - 向数组中存放与声明类型不兼容对象异常

indexoutofboundsexception - 下标越界异常

negativearraysizeexception - 创建一个大小为负数的数组错误异常

numberformatexception - 数字格式异常

securityexception - 安全异常

unsupportedoperationexception - 不支持的操作异常

五、使用finally进行清理

 class threeexception extends exception {}
 public class finallyworks {
  static int count = 0;
  public static void main(string[] args) {
   while(true) {
    try {
     if(count++ == 0) {
      throw new threeexception();
     }
     system.out.println("no exception");
    } catch (threeexception e) {
     system.out.println("threeexception");
    } finally {
     system.out.println("in finally clause");
     if(count == 2) 
      break;
    }
   }
  }
 }

  这个程序给了我们一些思路(确实。。),如果把try块放在循环里,就建立了一个“程序继续执行之前必须要到达”的条件。

  还可以加入一个static类型的计数器或者别的装置,使循环在放弃之前能够尝试一定的次数。这将使程序的健壮性更上一个台阶(好叼的样子)。

  1)finally用来做什么

    当要把除内存之外的资源恢复到它们的初始状态时,就要用到finally子句。

  2)在return中使用finally

    因为finally子句总是会执行的,所以在一个方法中,可以从多个点返回,并且可以保证重要的清理工作仍旧会执行:

class threeexception extends exception {}
 public class finallyworks {
  static int count = 0;
  public static void main(string[] args) {
   while(true) {
    try {
     if(count++ == 0) {
      throw new threeexception();
     }
     system.out.println("no exception");
     return;
    } catch (threeexception e) {
     system.out.println("threeexception");
    } finally {
     system.out.println("in finally clause");
     if(count == 3) 
      break;
    }
   }
  }
 }

第一次循环,首先执行第7行,符合条件,抛出异常,执行catch块,最后执行finally清理,不符合第16行判断,继续循环

第二次循环,不符合第7行判断,抛出异常,并return,但依旧执行finally清理,不符合第16行判断,但try块中已经执行return,所以程序结束,输出:

threeexception
in finally clause
no exception
in finally clause

  3)java异常的缺憾:异常丢失

 public class exceptionsilencer {
  public static void main(string[] args) {
  try {
    throw new runtimeexception();
   } finally {
    return;
   }
  }
 }

以上就是java基础--如何通过异常处理错误的详细内容,更多关于java 通过异常处理错误的资料请关注移动技术网其它相关文章!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网