简体   繁体   中英

Manually throw an exception

如何在Java中手动抛出IndexOutOfBoundsException并选择性地打印消息?

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();
       }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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