
正文
自定义Exception
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
本文改编自http://blog.csdn.net/stellaah/article/details/6738424
[总结]
1.自定义异常:
class 异常类名 extends Exception {
public 异常类名(String msg) {
super(msg);
}
}
2.标识可能抛出的异常:
throws 异常类名1,异常类名2
3.捕获异常:
try{} catch(异常类名 y){} catch(异常类名 y){}
4.方法解释:
getMessage() //输出异常的信息
printStackTrace() //输出导致异常更为详细的信息
[代码]
// 自定义异常
class ZeroException extends Exception {
public ZeroException(String msg) {
super(msg);
}
} class NegtiveException extends Exception {
public NegtiveException(String msg) {
super(msg);
}
}
// 自定义异常 End class Calculate {
public int shang(int x, int y) throws ZeroException,NegtiveException {
if (y < 0) {
throw new NegtiveException("您输入的是" + y + ",规定除数不能为负数!");// 抛出异常
}
if (y == 0) {
throw new ZeroException("您输入的是" + y + ",除数不能为0!");
} int m = x / y;
return m;
}
} // main
public class AppTest {
public static void main(String[] args) {
Calculate calculate = new Calculate();
// 捕获异常
try {
System.out.println("商=" + calculate.shang(1, -3));
} catch (ZeroException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (NegtiveException e) {
System.out.println(e.getMessage());
}
}
}





