![](/img/trans.png)
[英]Not able to install TestNG on Eclipse Neon. Getting prompt for Username and password
[英]Disable Error Prompt/Warning in Eclipse Java Neon
我正在Eclipse中使用以下代碼:
public class Foo {
public static final Bar bar = new Bar(20);
}
public class Bar {
public int value;
// This needs to be able to be called in places other than
// just Foo, and there it will need to throw.
public Bar(int value) throws Exception {
if(value == 0) {
throw Exception("Error. Value cannot be 0 when constructing Bar.");
}
return;
}
}
這在Foo(第2行)中給了我一條錯誤消息,內容為“未處理的異常類型Exception”,即使在實踐中,此代碼也永遠不會發生此異常。 我可以在Eclipse中禁用此錯誤,以便它不會打擾我,還是我可以通過其他方法來處理此錯誤?
提前感謝您的回答!
這是一個編譯器錯誤,需要修復才能編譯Java代碼,而不是Eclipse問題: 被檢查的異常需要在Java中進行顯式處理 ,方法是用try
包圍它- catch
或傳遞異常(方法/構造函數throws
...)。 。
如果不能更改Bar
類,則一種可能性是使用私有靜態方法來初始化常量 bar
(根據Java命名約定應將其命名為BAR
):
public class Foo {
public static final Bar BAR = initBar(20);
private static Bar initBar(int value) {
try {
return new Bar(20);
} catch (InvalidCharacterException e) {
return null;
}
}
}
用try / catch包圍構造函數以捕獲異常。
像這樣:
public class Foo {
try {
public static final Bar = new Bar(20);
}catch(InvalidCharacterException e) {
e.PrintStackTrace();
}
應該解決您的問題。 如果沒有,請隨時回復,我會盡力幫助您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.