Throwing Exceptions

When you call a method of another class, that class can control how the method is used by throwing exceptions.

As you make use of the classes in the Java class library, the compiler often displays a message such as the following:

Output

NetReader.java:14: unreported exception java.net.MalformedURLException; must be caught or declared to be thrown

Whenever you see an error stating that an exception “must be caught or declared to be thrown,” it indicates the method you are trying to use throws an exception.

Any class that calls these methods, such as an application that you write, must do one of the following things:

• Handle the exception with a try-catch block.

• Throw the exception.

• Handle the exception with a try-catch ...

Get Sams Teach Yourself Java™ in 24 Hours, Sixth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.