• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

java 搞代码 4年前 (2022-01-09) 24次浏览 已收录 0个评论
文章目录[隐藏]

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

一、创建自定义异常

package Exception; 
 class SimpleException extends Exception{}
 
 public class InheritingException{
  
  public void f() <a style="color:transparent">本文来源gao($daima.com搞@代@#码$网</a>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标准异常


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:JAVA基础–如何通过异常处理错误

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址