未在 Eclipse 中处理的异常类型 Exception

huangapple go评论80阅读模式
英文:

Unhandled exception type Exception in Eclipse

问题

我有一个在Java中的Parser类,如下所示:

public class Parser {
    public ArrayList<MetroStop> listeArrets;

    public Parser() {
        this.listeArrets = new ArrayList<>();
    }

    public MetroStop creerArret(String[] parts) {
        MetroStop arret = new MetroStop();
        arret.identifiant = Integer.parseInt(parts[0]);
        arret.longitude = Double.parseDouble(parts[1]);
        arret.latitude = Double.parseDouble(parts[2]);
        arret.nom = parts[3];
        arret.destination = parts[4];
        arret.moyen = parts[5];
        return arret;
    }

    public void parse(String fichier) throws Exception {
        try {
            Reader reader = new FileReader(fichier);
            BufferedReader br = new BufferedReader(reader);
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("#");
                MetroStop arret = creerArret(parts);
                listeArrets.add(arret);
            }
            br.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

我还有一个Main类:

public class Main {
    public static void main(String[] argv) {
        Parser teste = new Parser();
        try {
            teste.parse("ratp_arret.csv");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

当我将Main类作为Java应用程序运行时,我得到以下错误:"Unhandled exception type Exception",它指向main()方法的第二行。文件ratp_arret.csv位于src文件夹中,这也是工作目录。我正在使用Eclipse。我不明白这个错误从哪里来。谢谢您的帮助!

英文:

I have the class Parser in Java like below:

public class Parser {
public ArrayList&lt;MetroStop&gt; listeArrets;

public Parser() {
	this.listeArrets = new ArrayList&lt;&gt;();		
}

public MetroStop creerArret(String [] parts) {
	MetroStop arret = new MetroStop ();	
	arret.identifiant = Integer.parseInt(parts [0]);
	arret.longitude = Double.parseDouble(parts [1]);
	arret.latitude = Double.parseDouble(parts [2]);
	arret.nom = parts [3];
	arret.destination = parts [4];
	arret.moyen = parts [5];
	return arret;
}

public  void  parse(String fichier)  throws  Exception {
	try {
		Reader reader = new FileReader(fichier);
		BufferedReader  br = new  BufferedReader(reader);
		String line;	
		while((line = br.readLine ()) != null) {
			String [] parts = line.split(&quot;#&quot;); 
			MetroStop arret = creerArret(parts);
			listeArrets.add(arret);		
		}
		br.close();
	} catch (FileNotFoundException e) {
        throw new RuntimeException(e);		
    }
}

}

I also have the Main class:

public class Main {
public static void main(String[] argv) {	
	Parser teste = new Parser();
	teste.parse(&quot;ratp_arret.csv&quot;);
}

}

When I run the Main class as Java Application i get this error:
"Unhandled exception type Exception", which points to the second line of the main() method.
The file ratp_arret.csv is located in the src folder, which is also the working directory.I am using Eclipse.
I don't understand where this error comes from.
Thank you for your help!

答案1

得分: 2

你调用了 teste.parse(someString),其中 teste 是一个类型为 Parser 的表达式。这意味着这是对你的 Parser 类型中的 parse(String) 方法的调用...

并且该方法被声明为 throws Exception

异常是一种传达备选返回选项的机制。parse 方法可以以两种方式之一完成:它可以“返回”,在这种情况下,它不返回任何内容(void),或者它可以“抛出”。它可以抛出的内容受限于它的 throws 行 - 在这种情况下,它几乎可以抛出任何东西(Exception 是几乎所有可抛出内容的超类型)。

Java 处理这个问题的方式是,你的代码需要处理方法可能结束的每一种可能方式。

因此,当 parser() 方法返回时,你的代码需要有一条路径(这很简单;它是一个 void 方法,你不需要为此编写任何特殊的代码),但是你还需要为另一种退出情况提供路径:当它抛出异常时。对于 RuntimeException,你会自动处理,但是对于其他异常,你有两个选项:

捕获它:

try {
    teste.parse(someString);
    // 这段代码在“返回”情况下运行。
} catch (Exception e) {
   // 这段代码在“抛出异常”情况下运行。
}

这将意味着你知道当你的 parse 方法决定通过 throws 路径退出时该怎么做。

或者,你可以通过让你的主方法也“分叉”来解决这个问题,并宣布它有两种完成方式:要么通过“返回”路径,要么通过“抛出”路径:

public static void main(String[] args) throws Exception {
    teste.parse(someString);
}
// 这个主方法已经声明它有两种不同的退出路径。即“返回”和“抛出异常”。

Java 将通过运行其主方法来启动一个应用程序,而且 Java 可以处理具有两个备选退出路径(返回或抛出异常)的 main 方法。它通过什么都不做来处理“返回”路径。它通过打印异常的类型、消息、堆栈跟踪和整个因果链来处理“抛出异常”路径。这是一个很好的默认设置,你不应该尝试通过捕获异常并尝试“记录”它来得出不同的结果。

解决方法:只需将 throws Exception 添加到你的主方法声明中。将 throws Exception 重新放在你的 parse 方法上,忽略 @Eritrean 的建议。

注意:所有方法在本质上都被声明为好像它们说了 throws RuntimeException, Error(也就是说,任何错误和任何运行时异常都可以在不写 throws 子句的情况下抛出,因为所有方法已经隐含具有该子句),这就是我之前所说的 RuntimeExceptions 可以“免费处理”的原因。思想是所有继承自 RuntimeException 的异常都是如此普遍或如此不太可能的情况,将其管理强加给程序员将会很不方便。这就是为什么你永远不需要编写 throws NullPointerExceptionthrows InternalError

英文:

You call teste.parse(someString), where teste is an expression which has type Parser. That means this is a call to the method parse(String) in your Parser type....

and that is declared with throws Exception.

Exceptions are a mechanism to convey alternate return options. The parse method can run its course in one of two ways: It can 'return', in which case it returns nothing (void), or, it can 'throw'. What it can throw is limited by its throws line - in this case, it can throw just about anything (Exception is the supertype of almost all things you can throw).

The way java handles this is that your code needs to handle every possible way a method can conclude.

So, you need a 'path' for your code when the parser() method returns (this is trivial; it's a void method, you get that 'for free', you don't need to write anything special for this), but you also need a path for that other exit scenario: When it throws something. You get handling of RuntimeException for free, but for others, you have two options:

catch it:

try {
    teste.parse(someString);
    // this code runs in the &#39;return&#39; case.
} catch (Exception e) {
   // this code runs in the &#39;throws&#39; case.
}

this would imply you know what to do when your parse method decided to exit via the throws path.

Alternatively, you fix this by having your main method also 'fork', and decree that it has two ways to finish: Either via the return route or the throw route:

public static void main(String[] args) throws Exception {
    teste.parse(someString);
}
// this main method has declared that it has two separate
// exit routes. &#39;return&#39;, and &#39;throws something&#39;.

java will start an application by running its main method, and java can deal with a main that has two alternate exit routes (return, or throw something). It handles the 'return' route by doing nothing. It handles the 'throw something' route by printing the type of the exception, the message, the stack trace, and the entire causal chain. That is an excellent default, and you should not attempt to come up with a different one by e.g. catching that exception and attempting to 'log it'.

This: Just add throws Exception to your main method declaration. Put the throws Exception back on your parse method, ignore @Eritrean's advice.

NB: All methods are inherently declared as if they said throws RuntimeException, Error (as in, any error and any runtimeexception can be thrown without writing a throws clause for it, as all methods implicitly have that clause baked in already), this is why I said earlier that RuntimeExceptions are 'handled for free'. The idea is that all exceptions that subclass RuntimeException are things that are so universal or so unlikely, it would be unwieldy to force management of this onto the programmer. That's why you never need to write throws NullPointerException or throws InternalError.

答案2

得分: 0

public void parse(String fichier) {
    try {
        // ...
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }
}

你抛出了 RuntimeException这被称为 **非检查异常**在方法声明中不需要强制声明这些异常并且在调用方法时也不需要捕获它
英文:
public  void  parse(String fichier)  /*throws  Exception*/ {
    try {
        // ...
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);      
    }
}

You throw RuntimeException. This is called not-checked exception and it's not mandatory to declare these exeptions in the method declaration and catch it when calle the method.

huangapple
  • 本文由 发表于 2020年10月19日 01:45:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/64416430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定