简体   繁体   English

抛出异常的方法:实际处理的位置是什么?

[英]Method with throws Exception: Where is it actually handled?

Here is an example code, I am throwing an exception here, it works perfectly fine without the try/catch block of code for some reason. 这是一个示例代码,我在这里抛出一个异常,由于某种原因,它没有try / catch代码块就可以正常工作。

Do I have to handle this inside this method "EntryDelete" or Do I have to handle this where the method is called from? 我是否必须在此方法“EntryDelete”中处理此问题,或者我必须处理调用此方法的方法吗? If so can I see an example, what do I have to import in there? 如果是这样我可以看到一个例子,那里我需要输入什么? What is the acceptable syntax or method to do this? 这样做的可接受的语法或方法是什么?

public boolean EntryDelete(int entryId) throws SQLException{
    this.open();
    kDatabase.delete(kENTRY_TABLE, kENTRY_ENTRY_ID + "=" + entryId, null);
    this.close();
    return true;            
}   

Edit: Whats the thought on handling the exception in both inside and outside the method? 编辑:在方法的内部和外部处理异常的想法是什么?

Whats the benefits of handling inside the method, whats the benefits of handling it outside of the method? 在方法内部处理的好处是什么,在方法之外处理它的好处是什么?

Thanks 谢谢

The thrown exception is handled (thrown further or caught) by the caller of this method here, not this method itself. 抛出的异常由此方法的调用者处理(进一步抛出或捕获),而不是此方法本身。 Of course, you could handle it here as well by adding the try-catch here, but as it currently is your method forces the caller to handle the possibly thrown exception. 当然,你可以在这里添加try-catch来处理它,但是因为它当前是你的方法强制调用者处理可能抛出的异常。

In response to your added question: 回答您添加的问题:

"Whats the benefits of handling inside the method, whats the benefits of handling it outside of the method?" “在方法内处理的好处是什么,在方法之外处理它的好处是什么?”

Sadly, the most comprehensive correct answer I can think of is that the advantage of dealing with the exception inside the method is not having to deal with it outside the method. 遗憾的是,我能想到的最全面的正确答案是,在方法中处理异常的优点是不必在方法之外处理它。 In general, the sooner you handle the exception the better, because you don't usually want to force anyone calling your methods to prepare for any exceptions that aren't strictly necessary. 一般来说,越早处理异常就越好,因为你通常不想强迫任何调用你的方法的人为任何非必要的异常做准备。

Since the method has 既然方法有

throws SQLException

in the signature so the method calling this method will have to handle the exception. 在签名中,调用此方法的方法必须处理异常。

EDIT: There is no rule of thumb, but from you can use the following guideline 编辑:有没有经验法则,但是您可以使用下面的指南

If the client can take some alternate action to recover from the exception, then throw the exception. 如果客户端可以采取一些备用操作从异常中恢复,则抛出异常。 If the client cannot do anything useful, handle the exception. 如果客户端无法执行任何有用的操作,请处理异常。 By useful, I mean taking steps to recover from the exception and not just logging the exception. 有用的,我的意思是采取措施从异常中恢复,而不仅仅是记录异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM