您的位置:首页 > 编程语言 > Java开发

Java 中构建自己的异常类

2006-05-20 11:18 429 查看
创建testc.java文件:
package com.test.my;

public class testc {

 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
   testException();
  } catch (Exception e) {
   System.out.println(e.toString());
  }
 }
 
 public static String testException() throws Exception {

  if (true) throw new MyException("异常!");
  else return "";

 }

}

创建MyException.java文件:
/**
 *
 */
package com.test.my;

/**
 * @author 苏显斌
 *
 */
public class MyException extends Exception{
 private static final long serialVersionUID = -3076697639889780533L;
 
 public MyException() {
  super("我的异常!");
 }
 
 public MyException(String msg) {
  super(msg);
 }
 
 public String toString() {
  return super.toString();
 }
}

异常处理需要注意的一些问题:

1、在进行异常处理的时候,注意catch异常的优先级,比如最先应当捕获那个异常放在最前面的catch里面,依次类推,最后是Exception异常;

2、finally内只能进行一些清理工作,不要在里面进行赋值之类的操作,比如看下面的例子,结果和我们想像的会有一些冲突:
package com.test.my;

public class testc {

 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
   String result = testException();
   System.out.println(result);
  } catch (Exception e) {
   System.out.println(e.toString());
  }
 }
 
 public static String testException() throws Exception {
  String result = "";
  try {
   // if (true) throw new MyException("异常!");
   int i = 0;
   int b = 10 / i;
  } finally {
   result = "正常!";
  }
  
  return result;
 }

}

得到的结果是:java.lang.ArithmeticException: / by zero
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息