如何正确使用异常方法GetMessage
我有以下Java代码:
System.out.print("\fPlease Enter an integer: ");
while(!validInt){
try{
number = kb.nextInt();
validInt = true;
}catch(InputMismatchException e){
System.out.print("Pretty please enter an int: ");
System.out.print(e.getMessage());
kb.nextLine();
continue;
)
kb.nextLine();
}
如何设置e.getMessage(),以便system.out.println(e.getMessage())将打印“ Pretty请输入INT:”
I have the following java code:
System.out.print("\fPlease Enter an integer: ");
while(!validInt){
try{
number = kb.nextInt();
validInt = true;
}catch(InputMismatchException e){
System.out.print("Pretty please enter an int: ");
System.out.print(e.getMessage());
kb.nextLine();
continue;
)
kb.nextLine();
}
how can I set e.getMessage() so that System.out.println(e.getMessage()) will print "Pretty please enter an int: "
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您仅在创建异常时设置消息,这是构造函数的参数。在您的情况下,如果像这样创建了InputMismatchException,那将是不错的:
tnrow new InputMismatchException(“ pretty请输入int:”),
因为您可能没有创建InputMismatchException,因此您无法设置它的消息,但是在一个内部,但是抓住您可以做一些像这样的事情:
然后,上面的人可以捕获该异常,并且会有适当的错误消息。
这显然有点尴尬,这就是为什么通常不使用这种方式的原因。
注意:
您通常不应该重复使用Java例外,而应该创建自己的例外。这很烦人,我几乎总是重复使用IllegalArgumentException或IllegalStateException,因为这些是很好的,可重复使用的例外,并描述了您想在上面讨论的“捕获和重新恢复”的常规代码“捕获和rethrow”例外的大多数原因。
You only set the message when the exception is created, it's an argument to the constructor. In your case it would have been nice if the InputMismatchException was created like this:
tnrow new InputMismatchException("Pretty please enter an int: ")
Since you probably aren't creating the InputMismatchException, you can't set it's message, however inside a catch you can do something liket this:
Then someone above you can catch that exception and will have an appropriate error message.
This is obviously a bit awkward which is why it usually isn't used this way.
Note:
You aren't usually supposed to re-use java exceptions but create your own. This is pretty annoying and I almost always re-use either IllegalArgumentException or IllegalStateException Because those are good, reusable exceptions and describe most of the reasons you'd want to throw in general code for "Catch and rethrow" exceptions as I discussed above.