1

So, in the documentation for example: java.lang.Integer.parseInt, I noticed that the code header is:

public static int parseInt(String s) throws NumberFormatException

However, when one has a statement something like int i = Integer.parseInt(someString); the code compiles fine without a try-catch block.

Now, on the other hand, if I write a method with the header:

public void connectTo(String ip) throws java.net.HostNotFoundException

and make a call to it without surrounding the call with a proper try-catch block, the compiler just won't have it. I'm not suggesting that I (or anyone) would want to surround every single Integer.parseInt call (and others) with a try-catch block, but I sure am curious as to why the compiler allows it.

Jonah Haney
  • 521
  • 3
  • 12

2 Answers2

2

Because NumberFormatException subclasses IllegalArgumentException, which in turn subclasses RuntimeException.

Subclasses of RuntimeException, unlike those of Exception, do not need to be explicitly caught (although they can be).

From the RuntimeException javadoc page:

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

Majora320
  • 1,321
  • 1
  • 13
  • 33
1

Because those exceptions are unchecked

From the attached link:

Because the Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeException, Error, and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException. Both of these shortcuts allow programmers to write code without bothering with compiler errors and without bothering to specify or to catch any exceptions. Although this may seem convenient to the programmer, it sidesteps the intent of the catch or specify requirement and can cause problems for others using your classes.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Cripto
  • 3,581
  • 7
  • 41
  • 65