创建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