在Java中,预定义的异常会自动抛出。例如:
int a=10, b=0;
c = a/b;
抛出算术异常
int a[3] = {1, 2, 3};
int b = a[4];
抛出ArrayOutOfBoundException
在用户自定义异常的情况下,我们应该创建一个该异常类的对象并手动抛出。我能否创建自己的异常来像上述两种情况一样运作?
try {
int a=10, b=0;
int c=a/b;
catch (Exception e){
//disregard exception, throw your own
throw new MyCustomException("My Custom Message");
}
或者,如果您有某种情况,希望在通常不存在异常的情况下抛出异常,那么只需抛出即可!
// In this case, only move forward if a < b
int a = 10, b = 0;
if (a >= b)
throw new MustBeLessThanException("a must be less than b!");
或者像那样的一些愚蠢的东西。
确保自定义类扩展Exception或其子类之一。
不,你只能捕获并抛出自己的异常:
try {
int a=10, b=0;
c = a/b;
} catch (ArithmetikException e) {
throw MyException("Bad!", e); // pass in e to getr a meaningful stacktrace
}
但我真的不建议这样做(除非你必须这样做,例如在实现一个没有声明可能在你的代码中抛出异常的接口时)。但是,你的例子都是RuntimeExceptions(未经检查的异常),这些异常不需要声明。