熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

異常的捕獲和實現自己的異常類

2022-06-13   來源: Java核心技術 

  /**
  * <p>Title: 捕獲異常和實現自己的異常類</p>
  * <p>Description: 通過繼承Exception類來實現自己的異常類並使用try-catch來捕獲這個異常</p>
  * <p>Copyright: Copyright (c) </p>
  * <p>Filename: </p>
  * @version
  */
  class MyException extends Exception {
  public MyException() {}
  public MyException(String msg) {
  super(msg);
  }
  public MyException(String msg int x) {
  super(msg);
  i = x;
  }
  public int val() { return i; }
  private int i;
  }
  
  public class DemoException {
  /**
  *<br>方法說明使用MyException類中默認的構造器
  *<br>輸入參數
  *<br>返回類型
  */
  public static void a() throws MyException {
  Systemoutprintln(
  Throwing MyException from a());
  throw new MyException();
  }
  /**
  *<br>方法說明使用MyException類中帶信息的構造器
  *<br>輸入參數
  *<br>返回類型
  */
  public static void b() throws MyException {
  Systemoutprintln(
  Throwing MyException from b());
  throw new MyException(Originated in b());
  }
  /**
  *<br>方法說明使用了MyException中有編碼的構造器
  *<br>輸入參數
  *<br>返回類型
  */
  public static void c() throws MyException {
  Systemoutprintln(
  Throwing MyException from c());
  throw new MyException(
  Originated in c() );
  }
  public static void main(String[] args) {
  try {
  a();
  } catch(MyException e) {
  egetMessage();
  }
  try {
  b();
  } catch(MyException e) {
  etoString();
  }
  try {
  c();
  } catch(MyException e) {
  eprintStackTrace();
  Systemoutprintln(error code: + eval());
  }
  }
  } //end
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25709.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.