我在Java中遇到异常处理问题,这是我的代码。当我尝试运行此行时出现编译器错误:throw new MojException("Bledne dane");
。错误是:
异常MojException永远不会在相应的try语句的主体中抛出
以下是代码:
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);
}
}
任何人都可以帮我吗?
答案 0 :(得分:17)
try语句中的catch-block需要捕获完全 try {}
- block 中的代码抛出的异常(或超类)那个)。
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知道您正在尝试捕获永远不会发生的异常。因此,你会得到:exception ExceptionA is never thrown in body of corresponding try statement
。
答案 1 :(得分:8)
正如评论中所指出的,您无法捕获try
块中代码未引发的异常。尝试将代码更改为:
try{
Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
}
catch(NumberFormatException e){
throw new MojException("Bledne dane");
}
始终检查documentation以查看每种方法引发的异常。您可能还希望在此之前阅读checked vs unchecked exceptions的主题,以免将来引起任何混淆。
答案 2 :(得分:0)
永远记住,在检查异常的情况下,你只能在抛出异常之后捕获(无论是你抛出还是你的代码中使用的任何内置方法都可以抛出),但是在未经检查的异常的情况下你甚至在没有抛出的情况下捕获那个例外。
答案 3 :(得分:0)
任何扩展Exception
类的类都将是用户定义的Checked异常类,其中任何扩展RuntimeException
的类都将是未经检查的异常类。
如User defined exception are checked or unchecked exceptions中所述
因此,不抛出已检查的异常(无论是用户定义的异常还是内置异常)都会产生编译时错误。
检查异常是在编译时检查的异常。
未经检查的异常是在编译时未检查的异常