简体   繁体   English

如何在Eclipse中为可选的Java异常生成代码

[英]How to generate code for an optional Java exception in Eclipse

I have some code that is parsing an int from a string: 我有一些代码从字符串中解析一个整数:

int number = Integer.parseInt(a[0]);

there is no guarantee that the string I will receive is well formed and this may throw a NumberFormatException. 无法保证我将收到的字符串格式正确,并且可能会引发NumberFormatException。 However, as this exception is optional, Eclipse does not give me a light bulb for generating it. 但是,由于此异常是可选的,因此Eclipse并没有为我提供生成它的灯泡。

Is there a menu or context menu option to wrap an exception of a method beneath the cursor or carrot? 是否有菜单或上下文菜单选项可将方法的异常包装在光标或胡萝卜下面?

It wont as NumberFormatException is a RuntimeException . 因为NumberFormatExceptionRuntimeException ,所以不会。

Imagine all the hard work eclipse would have to do to catch null pointer exceptions.Eclipse would only tell you about checked Throwables 想象一下,所有的辛苦工作都会使Eclipse捕获空指针异常,而Eclipse只会告诉您有关检查过的Throwables的信息

Highlight the block you want to enwrap, go to the top menu under Source . 突出显示要包装的块,然后转到“ Source下的顶部菜单。 Choose Surround with Try / Catch Block . 选择“ Surround with Try / Catch Block

It will automatically indent the code and list the found exceptions. 它将自动缩进代码并列出找到的异常。 I think the NumberFormatException will be listed automatically. 我认为NumberFormatException将自动列出。

This is basically the same as with UncheckedExceptions, except that with UncheckedExceptions Eclipse will automatically highlight the line as it is a Java Error to ignore (not catch nor rethrow) a checked exception. 这与UncheckedExceptions基本相同,不同之处在于,对于UncheckedExceptions,Eclipse将自动突出显示该行,因为它是忽略(不捕获也不重新抛出)已检查异常的Java错误。 You probably have used the QuickFix Menu (usually STRG+1 as hotkey, or mouse hover over the error). 您可能已经使用了QuickFix菜单(通常将STRG + 1作为热键,或将鼠标悬停在错误上)。 The menu item above will work even without an error (and thus no error you could use QuickFix for) 上面的菜单项即使没有错误也可以工作(因此可以使用QuickFix进行操作没有错误)

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

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