开发者

Manually throw an exception

How would I manually throw an Inde开发者_运维百科xOutOfBoundsException in Java and optionally print a message?


You simply:

throw new IndexOutOfBoundsException("your message goes here");

If you need to print that message, do so from where you catch the exception. (You can reach the message with the getMessage() method.)


Like this:

throw new IndexOutOfBoundsException("If you want a message, put it here");

This doesn't actually print the message; it just prepares it. To print the message, do something like the following:

try {
    //...
    throw new IndexOutOfBoundsException("If you want a message, put it here");
} catch (IndexOutOfBoundsException e) {
    System.out.println(e.getMessage());
}

In the future, I'd suggest looking around for an answer before posting.


You can use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.

throw someThrowableObject;

Example:

    public void example() {
       try{
            throw new IndexOutOfBoundsException();
       } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
       }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜