Java 如何加上「;“抛出异常”;这个代码?

Java 如何加上「;“抛出异常”;这个代码?,java,arrays,try-catch,bluej,Java,Arrays,Try Catch,Bluej,这是我的密码 public int Test(int[]n){ if(n.length!=0){ int smallest = n[0]; for(int i = 0; i<n.length ; i++){ if(smallest > n[i]){ smallest = n[i]; return smallest; }else{

这是我的密码

 public int Test(int[]n){
    if(n.length!=0){
        int smallest = n[0];
        for(int i = 0; i<n.length ; i++){
            if(smallest > n[i]){
                smallest = n[i];
                return smallest; 
            }else{
            return 0; 
        }
    }

}
public int测试(int[]n){
如果(n.长度!=0){
int最小值=n[0];
for(int i=0;i n[i]){
最小值=n[i];
返回最小;
}否则{
返回0;
}
}
}

如何更改此代码,使其在列表为空时抛出异常而不是返回零

您可以简单地实现您的目标:

 public int Test(int[] n) {
    if (n.length != 0) {
        int smallest = n[0];
        for (int i = 0; i < n.length; i++) {
            if (smallest > n[i]) {
                smallest = n[i];
            }
        }
        return smallest;
    } else {
        throw new RuntimeException("List is empty!");
    }
}
public int测试(int[]n){
如果(n.长度!=0){
int最小值=n[0];
for(int i=0;in[i]){
最小值=n[i];
}
}
返回最小;
}否则{
抛出新的RuntimeException(“列表为空!”);
}
}

您可以按如下方式修改else块:

if(n.length!=0){
    int smallest = n[0];
    for(int i = 0; i<n.length ; i++){
        if(smallest > n[i]){
            smallest = n[i];
            return smallest; // you might want to change this as well as suggested by @saeid
        } else {
            throw new CustomException(); 
        }
    }
}
if(n.length!=0){
int最小值=n[0];
for(int i=0;i n[i]){
最小值=n[i];
return minimable;//您可能希望按照@saeid的建议对此进行更改
}否则{
抛出新的CustomException();
}
}
}

其中
CustomException
可以扩展您可能想要抛出的任何异常。

您只需检查空列表,如果它是空的,只需抛出异常即可

    throw new Exception("Your message that you want to show whenever the list is empty").
否则

创建自定义异常类

    class ListIsEmptyException extends Exception{
       //create constructors as per your need
    }
现在如果列表为空

    throw new ListIsEmptyException();

return语句不能在内部“if块”中,因为它返回if首次比较成功。但这取决于您必须返回方法的位置。试试这个代码

创建自定义异常

公共类自定义异常{

public customException(String msg) {

    super(msg);
}
}

if(n.length!=0){
int最小值=n[0];
for(int i=0;i n[i]){
最小值=n[i];
返回最小;
}否则{
抛出新的customException(“它是一个空列表!!!”);
}
}

当您不想返回“int”返回类型时,为什么会有“int”返回类型?糟糕!忘记了返回声明@In6ify要抛出哪个异常?
if(n.length!=0){
    int smallest = n[0];
    for(int i = 0; i<n.length ; i++){
        if(smallest > n[i]){
            smallest = n[i];
            return smallest; 
        }else{
            throw new customException("Its an empty list!!!"); 
    }
}