-1

For example, if I don't handle the NumberFormatException thrown by Integer.parseInt(), it could be complied; however, if I use the Thread.sleep() without a try-catch, there would be the unhandled exception error. Why?

Paul Zhang
  • 305
  • 2
  • 7

3 Answers3

2

Read the difference between checked exceptions (mandatory to be handled), and non-checked exceptions (optional to be handled) in Java.

1

NumberFormatException extends RuntimeException. Runtime exceptions are unchecked exceptions and do not need to be caught

m0skit0
  • 25,268
  • 11
  • 79
  • 127
0

In short, if a method declares that it might throw an exception, compiler will force you to handle (with catch block) or redeclare it in case that exception is itself or subclass of Exception class.In opposite, if the declared exception is itself or subclass of RuntimeException class, compiler will stay silent and doesn't force you to do something. I also strongly recommend to look into differences between unchecked and checked exceptions as was said in other answers.