[英]Do we need to throw the same exception in catch block which is already mentioned in method signature using throws declaration
I have a method in my Java App which throws SQLException
. 我的Java应用程序中有一个抛出
SQLException
。 Is it necessary to throw the SQLException
in the catch block so that the exception is thrown to the calling method where the exception is handled? 是否有必要将
SQLException
在catch块中,以便将异常抛出到处理该异常的调用方法?
public void insert(Connection conn) throws SQLException
{
try {
// my code
} catch (SQLException s) {
throw s;
}
}
If you want to handle the exception yourself and then pass it to the calling method, then yes, you will need to re-throw it: 如果要自己处理该异常,然后将其传递给调用方法,则可以,您将需要重新抛出该异常:
public void insert(Connection conn) throws SQLException {
try {
// Your code.
} catch (SQLException s) {
// Handle s.
throw s;
}
}
If you don't need to do anything with the exception and just want to pass it to the calling method then you can just omit the try
- catch
and if an exception is thrown the calling method will receive it: 如果您不需要对异常做任何事情,而只想将其传递给调用方法,则可以省略
try
- catch
,如果引发异常,则调用方法将收到该异常:
public void insert(Connection conn) throws SQLException {
// Your code.
}
The error occur because you place your code inside a 'try-catch' block, if any exception will happen the catch block handle with it. 发生该错误是因为将代码放置在“ try-catch”块内,如果发生任何异常,catch块句柄也会随之发生。 not send to the calling method.
不发送给调用方法。
You can use the below function to thrown the exception to the calling method 您可以使用以下函数将异常抛出给调用方法
public void insert(Connection conn) throws SQLException {
//code.
}
If you declare exception in throws clause of the method, then you can: 如果在方法的throws子句中声明异常,则可以:
1) throw exception of declared type. 1)抛出声明类型的异常。
2) throw exception of subtype of declared type. 2)抛出声明类型子类型的异常。
3) swallow the exception. 3)吞下异常。 (Not recommended as you have declared it in signature)
(不建议使用,因为您已经在签名中声明了它)
4) throw any other runtime exception. 4)抛出任何其他运行时异常。
Now coming to your example, It would be good to re-throw the exception so that the caller method knows that something wrong happened and take appropriate action (eg if a transaction is running on the Connection object then roll-back the transaction). 现在来看您的示例,最好抛出异常,以便调用方方法知道发生了什么错误并采取适当的措施(例如,如果事务在Connection对象上运行,则回滚该事务)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.