如何在Java中抛出异常
在Java中,当你想要程序因为某种错误状态而停止执行时,可以使用throw
关键字来抛出一个异常。
以下是一个简单的例子,我们创建一个方法,如果输入的数字不是正数,就抛出一个ArithmeticException
:
public class ExceptionExample {
public void checkNumber(int number) throws ArithmeticException {
if (number <= 0) {
throw new ArithmeticException("Input number must be positive.");
}
}
public static void main(String[] args) {
ExceptionExample example = new ExceptionExample();
try {
example.checkNumber(-1);
} catch (ArithmeticException e) {
System.out.println(e.getMessage()); // Output: Input number must be positive.
}
}
}
在这个例子中,checkNumber
方法检查传入的数字是否为正数。如果输入的是负数或零,就会抛出一个ArithmeticException
。在main
方法中的try-catch
块就是用来捕获并处理这个异常的。
还没有评论,来说两句吧...