在Java中引发异常 [英] Throw exception in Java

查看:147
本文介绍了在Java中引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类,要求是如果 den为0,则更改以下代码以引发检查的异常,并更改函数以捕获该异常。

Suppose I have a class, the requirement is that "change the following code to throw checked exception if "den" is 0, and change the function to catch that exception".

public class divide {
void divide(int num, int den){
    System.out.println(""+(num/den));
}
void fun(){
    divide(4,2);
}
}

以下哪一项是正确的投掷方式

Which of the following one is the correct way to throw exception?

选项1:

void divide(int num, int den) throws Exception{
    if(den==0){
        throw new Exception("Dividebyzero");
    }
    System.out.println(""+(num/den));
}
void fun(){
    try {
        divide(4,2);
    } catch (Exception e) {
    } 
}

选项2:// //我认为这是正确的

Option 2: // I think this one is correct

void divide(int num, int den){
    if(den==0){
        throw new RuntimeException("Dividebyzero");
    }
    System.out.println(""+(num/den));
}
void fun(){
    try {
        divide(4,2);
    } catch (RuntimeException e) {
    } 
}

选项3:

void divide(int num, int den) throws Exception{
    if(den==0){
        throw new RuntimeException;
    }
    System.out.println(""+(num/den));
}
void fun(){
    try {
        divide(4,2);
    } catch (Exception, RuntimeException) {
    } 
}

此问题来自Java练习之一。我已经学过Java几年了,但是我对尝试捕获感到困惑。我个人认为选项2是正确的,因为我们只抛出一次异常,否则我错了?

This problem came from one of the Java exercises. I have learned Java for several years but I am kind of confused about the try catch throw. Personally, I think that option 2 is correct because we only throw the exception once, or I am wrong?

推荐答案


以下哪个是引发异常的正确方法?

Which of the following one is the correct way to throw exception?

我不会使代码复杂化,而是会使用已经抛出的异常。

I wouldn't complicate the code, instead I would use the exception it already throws.

void printDivide(int num, int den) throws ArithmeticException {
    System.out.println(num / den);
}

使用不同的异常不仅更加复杂,而且令人困惑。

Using a different exception is not just more complicated, it's confusing.

让我们设置一个不同的示例,然后IllagelArgumentException是非法参数的好选择,例如创建数组

Lets set it is a different example, then IllagelArgumentException is a good choice for an illegal argument, like creating an array

void createArray(int size) {
    if (size < 0)
        throw IllegalArgumentException("Size must be non-negative " + size);
    this.array = new int[size];
}

这篇关于在Java中引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆