抛出错误的异常 [英] Wrong exception being thrown

查看:55
本文介绍了抛出错误的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算1到12之外的任何值或一个月的名字。我正在传递一个字符串到这个方法。然后我尝试将它解析为一个int并执行一个if语句来查看它是否介于1和12之间。如果它不是一个int,那么它会关闭并且for循环检查它是否''一个月的名字。


问题是,如果我向catch块添加一个新的IllegalArgumentException并传入Saturday,它会抛出非法月份号消息,而不是无效的月份名称字符串消息。如果我将catch块留空,则1到12范围之外的数字会下降并抛出无效月份名称字符串消息。

I''m trying to account for any value outside of 1 to 12 or a name of a month. I''m passing in a string to this method. I then try to parse it into an int and do an if statement to see if it''s between 1 and 12. If it''s not an int then it goes down and a for-loop checks to see if it''s a name of a month.

The problem is that if I add a throw new IllegalArgumentException to the catch block and pass in "Saturday" it throws the Illegal month number here message instead of Invalid month name string message. If I leave the catch block empty, then numbers outside the range of 1 to 12 go down and throw the Invalid month name string message.

展开 | 选择 < span class =codeDivider> | Wrap | 行号

推荐答案

我们知道如果我们进去,它不是一个数字catch之后没有捕获,所以你的字符串逻辑必须进入catch块。

We know it''s not a number if we get inside the catch not after the catch so your string logic must go inside the catch block.

展开 | 选择 < span class =codeDivider> | Wrap | 行号


使用我发布的代码,诸如1月之类的字符串。或星期六或正确地被hanlded,但是1到12之外的数字被发送到第二个IllegalArgumentException而不是第一个并给出错误的System.out.print()消息。


如果我向catch块添加一个新的IllegalArgumentException,那么1到12之外的数字会被正确处理,但是诸如January之类的字符串会被处理掉。或星期六或正在被赋予第一个IllegalArgumentException而不是第二个,并给出错误的System.out.print()消息。


所以无论哪种方式,它都不适用于这两种类型输入。
With the code I posted, strings such as "January" or "Saturday" were being hanlded correctly, but numbers outside of 1 to 12 were being sent down to the 2nd IllegalArgumentException instead of the 1st one and giving the wrong System.out.print() message.

If I add a throw new IllegalArgumentException to the catch block, then numbers outside of 1 to 12 get handled correctly, but strings such as "January" or "Saturday" are being given the 1st IllegalArgumentException instead of the 2nd one, and giving the wrong System.out.print() message.

So either way, it''s not working for both types of input.


您发布的代码有一个空的catch块。将其与我发布的代码进行比较。
The code you posted has an empty catch block. Compare that with the code I posted.


这篇关于抛出错误的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆