简体   繁体   中英

beginner question about exception in java

when an exception occurs that a method is unable to handle - does the program terminate and show the error number ? where does the error number and information about the error come from ? should the programmer while coding have an idea what kind of exception might occur. if so why does'nt he ensure that exception does not occur .

If you are using Java APIs, the exceptions that each method throws are documented.

When the program terminate, it shows an stacktrace of the methods calls that caused that specific problem.

Check the lesson on Exceptions from The Java Tutorial . You can learn much more reading there than reading my answer here :)

There are 2 main types of exceptions in Java:

- checked
- unchecked

unchecked exceptions are further broken into RuntimeException and Error.

RuntimeExceptions are programmer errors (ArrayIndexOutOfBoundsException) and Errors are things that are problems in the VM (OutOfMemoryError).

You should not catch RuntimeExceptions - you should fix your code so it does not throw the exception.

You should not catch Errors since the VM is likely in a state that you cannot do anything to recover from them.

If your main does not catch an unchecked exception it will crash.

Java Exceptions bubble-up to the point where someone catches them, or to the point the program exits. In the real-world, when many frameworks are used, exceptions never bubble-up to the top. They are caught and reported (printed on console). Catching exceptions is done by the try { } catch(..) { } block.

There are two types of exceptions - checked and unchecked. The checked exceptions must be declared in the method signature (unlike the unchecked)

should the programmer while coding have an idea what kind of exception might occur

Yes, but no one's perfect.

why does'nt he ensure that exception does not occur

In exceptional circumstance, you WANT an exception. You do not want to ignore the exception. For example, suppose that your program creates a file to save user settings. If for some reason the file creation fails (which your program has no control over, it's the Operating System's job), you do not want to go on like nothing happened. You want there to be an exception, so that whoever or whatever function called that function knows about this problem, and can do something, eg inform the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM