-1

I have to handle file not found exception. But the file availablity will be known only during run time. Why i should handle it. also Null pointer or run time exception occurs during run time, that we do not handle?

  • Are you going to go to your customer's house and edit the code to add exception handling when runtime happens? – user2357112 Feb 24 '18 at 18:17
  • Possible duplicate of [When to choose checked and unchecked exceptions](https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions) – xingbin Feb 24 '18 at 18:19
  • My Question was why does compiler prompts to handle File not found if the real exception happens at run time and not for Null pointer – user2924500 Feb 24 '18 at 18:38

1 Answers1

1

The purpose of checked exceptions is to force you, the programmer, to intentionally either:

  1. Handle the exception, or

  2. Declare you expect the caller to handle it

This can go all the way up to main or whatever your program's main entry point is. So if you really want the entire program to crash and burn because the file couldn't be found, you could declare all of the methods leading up to that code as throwing FileNotFoundException.

More likely, you want to provide a better UX than that, by handling the error and showing the user a nicer error message.

In contrast, unchecked exceptions are for

  • Programming errors (you tried to access a property on null, index past the end of an array, etc.), and

  • Runtime errors the code won't be able to handle nicely, such as out-of-memory conditions.

You don't have to declare or handle those, because by the time the code is shipped to a user, testing should have gotten rid of all of the first type (programming errors), and there's nothing your code can do about the second type.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875