java
java

Reputation: 141

Manually throw an exception

How would I manually throw an IndexOutOfBoundsException in Java and optionally print a message?

Upvotes: 12

Views: 58535

Answers (3)

user4060017
user4060017

Reputation:

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

Upvotes: 3

fireshadow52
fireshadow52

Reputation: 6516

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.

Upvotes: 13

Mat
Mat

Reputation: 206689

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.)

Upvotes: 34

Related Questions