自定义异常类:
先看两个自定义异常:
// 异常1
class MyException extends Exception
{
public MyException(String msg)
{
super(msg);
}
}
// 异常2
public class BusinessRuntimeException extends RuntimeException {
public BusinessRuntimeException(String message) {
super(message);
}
public BusinessRuntimeException(String message, Throwable cause) {
super(message, cause);
}
public BusinessRuntimeException(Throwable cause) {
super(cause);
}
public BusinessRuntimeException(String message, Throwable cause, boolean enableSuppression,boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
自定义异常类怎么用?
如果不是catch(Exception ex)里的,直接:
throw new MyException("说明文字");
否则例如:
try {
} catch (IllegalAccessException e) {
throw new MyException("系统错误,请重试", e);
}
参考:
try {
产生异常的语句;
}
catch(Exception e) {
throw new MyException("...失败!",e);
}
// finally部分看需求要不要,如果还有需要执行的部分,就要finally,否则就不要。
finally {
}
// 例:
FileOutputStream out = null;
try {
out = new FileOutputStream(filePath);
wb.write(out);
}
catch (Exception e){
throw new BusinessRuntimeException("文件创建失败!",e);
}
finally {
try {
out.close();
}
catch (Exception e) {
throw new BusinessRuntimeException("关闭文件输出流失败!",e);
}
}
// 为什么wb.write(out);放在try块,而out.close();放在finally块?
析:如果文件创建失败,wb.write(out);就不需要执行,而放在finally里的是必须执行的代码。
有时不需要finally,有时操作必须写在finally里,比如输出流的关闭out.close(); ,因为如果写在try块里,上面的new FileOutputStream(filePath);会产生异常,就会catch住,然后直接就到finally块了,try里的剩下代码就不会执行了。