是否有可能在抛出异常的方法之外捕获异常?
举个例子:
public double[] readFile(String filename) throws IOException
{
File inFile = new File(filename);
Scanner in = new Scanner(inFile);
try
{
readData(in);
return data;
}
finally
{
in.close();
}
}如何在方法中捕获IOException?我能做catch(IOException){}吗?
发布于 2016-02-03 16:40:22
是的,tou可以这样做,捕获someMethod()方法中抛出的异常,如下所示:
public double[] readFile(String filename) throws IOException
{
...
}在另一种方法中,例如:
public void someMethod(){
try
{
readFile(in);
return data;
}catch(IOException io){
}
...
}发布于 2016-02-03 16:41:15
您不需要在此方法中使用try/catch语句,因为您不希望在内部处理异常,因此希望抛出异常。(这就是throws关键字的作用)
所以你可以这么做:
public double[] readFile(String filename) throws IOException
{
File inFile = new File(filename);
Scanner in = new Scanner(inFile);
readData(in);
// If everything goes normally, the execution flow shall pass on to
// the next statements, otherwise if an IOException is thrown, it shall
// be handled by the caller method (main)
in.close();
return data;
}&在main方法中,处理潜在的异常:
try {
double[] result = readFile("filename.ext");
// ...
}
catch(IOException e) {
// Handle the exception
}https://stackoverflow.com/questions/35182649
复制相似问题