2、(由方法抛出异常)编写一个Java程序,要求在程序中定义一个能抛出异常的方法,该方法接收三个参数,若第2个参数为0,则抛出算术异常,若第3个参数小于或等于0,则抛出空指针异常。在main()方法中捕获并处理该异常;
时间: 2024-03-20 22:38:38 浏览: 58
好的,我来为你编写这个Java程序:
```java
public class ExceptionDemo {
public static void main(String[] args) {
try {
int result = divide(6, 0, 5);
System.out.println("The result is: " + result);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: " + e.getMessage());
} catch (NullPointerException e) {
System.out.println("NullPointerException: " + e.getMessage());
}
}
public static int divide(int a, int b, int c) throws ArithmeticException, NullPointerException {
if (b == 0) {
throw new ArithmeticException("The second parameter cannot be zero.");
}
if (c <= 0) {
throw new NullPointerException("The third parameter must be greater than zero.");
}
return a / b + c;
}
}
```
在上面的代码中,我们定义了一个`divide`方法,它接收三个参数`a`、`b`和`c`。如果`b`为0,则抛出一个算术异常;如果`c`小于或等于0,则抛出一个空指针异常。在`main`方法中,我们调用`divide`方法,并使用`try-catch`语句捕获并处理可能抛出的异常。如果抛出了算术异常,则打印出异常信息;如果抛出了空指针异常,则也打印出异常信息。注意,我们在方法定义中使用了`throws`关键字来声明该方法可能会抛出哪些异常。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![ppt](https://img-home.csdnimg.cn/images/20241231044937.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/octet-stream](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)