当 anException
生成时,有两种处理方法。
- 处理异常 - 这使用
catch
块
- 声明异常 - 这使用
throws
块
因此,处理已经生成的异常是由catch
or完成的throws
。
另一方面,throw
在“生成”异常时使用。
通常,throw
在实例化 Exception 对象或将已生成的异常级联到调用者时使用关键字。
例如,
public void doSomething(String name) throws SomeException { // Exception declared
if( name == null ){ // cause of the exception
throw new SomeException(); // actual NEW exception object instantiated and thrown
}
// Do something here
.
.
.
}
在调用方法中,
public static void main(String[] args) throws SomeException{ // Need to declare exception because you're "throwing" it from inside this method.
try { // try doing some thing that may possibly fail
doSomething(name);
} catch (SomeException e){
throw e;// throw the exception object generated in doSomething()
}
}
或者,您可以在 catch 块中“处理”异常:
public static void main(String[] args) { // No need to declare exception
try { // try doing some thing that may possibly fail
doSomething(name);
} catch (SomeException e){
System.out.println("Exception occurred " + e.getMessage()); // Handle the exception by notifying the user.
}
}
希望这可以帮助。
附录 - 异常处理词汇表
try
- 用于调用可能导致异常的代码或文件/流/网络/数据库连接等资源。
catch
- 在try
块之后立即使用以“处理”或“抛出”异常。如果使用可选finally
。
finally
- 在 atry
或catch
块之后立即使用。可选的。用于执行“必须”执行的代码。finally
块中的代码总是被执行——即使try
orcatch
有一个return
语句。
throw
- 用于通过调用方法“推送”或“级联”异常。总是在方法内部使用。
throws
- 用于“声明”如果出现问题,方法将抛出异常。始终用作方法签名的一部分。
附加阅读
这是一篇详尽的文章,可帮助您理解 java 中的 try-catch-finally 语义。
更新
要回答你的另一个问题,
为什么我们不需要使用 catch , finally 阻止 throws IOException ?
将catch
和throws
视为相互排斥的结构。(这并不总是正确的,但为了您的理解,最好从这个想法开始。)
你声明它的一个方法throws IOException
。这段代码是在您声明方法的地方编写的。而且,从语法上讲,您不能将方法声明放在 try 块中。
throws 是如何处理异常的。?
就像我之前提到的,catch
在finally
异常处理期间使用。throws
只是用于将异常级联回调用者。