gpt4 book ai didi

java - 相应 try 语句的主体中永远不会抛出异常

转载 作者:太空宇宙 更新时间:2023-11-04 14:07:15 28 4
gpt4 key购买 nike

我在 Java 中遇到异常处理问题,这是我的代码。当我尝试运行此行时出现编译器错误:throw new MojException("Bledne dane");。错误是:

exception MojException is never thrown in body of corresponding try statement

这是代码:

public class Test {
public static void main(String[] args) throws MojException {
// TODO Auto-generated method stub

for(int i=1;i<args.length;i++){
try{
Integer.parseInt(args[i-1]);
}
catch(MojException e){
throw new MojException("Bledne dane");
}
try{
WierszTrojkataPascala a = new WierszTrojkataPascala(Integer.parseInt(args[0]));
System.out.println(args[i]+" : "+a.wspolczynnik(Integer.parseInt(args[i])));
}
catch(MojException e){
throw new MojException(args[i]+" "+e.getMessage());
}
}
}
}

这是 MojException 的代码:

public class MojException extends Exception{
MojException(String s){
super(s);
}
}

谁能帮我解决这个问题吗?

最佳答案

try 语句中的 catch block 需要准确捕获 try {} block 内的代码可以抛出的异常(或其父类(super class))。

try {
//do something that throws ExceptionA, e.g.
throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
//do something to handle the exception, e.g.
System.out.println("Message: " + e.getMessage());
}

您想要做的是:

try {
throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
System.out.println("Message: " + e.getMessage());
}

这将导致编译器错误,因为您的 java 知道您正在 try catch 永远不会发生的异常。因此,您将得到:异常 ExceptionA 永远不会在相应的 try 语句主体中抛出

关于java - 相应 try 语句的主体中永远不会抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28725981/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com