fesam
fesam

Reputation: 215

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 .

Upvotes: 1

Views: 537

Answers (4)

JRL
JRL

Reputation: 77995

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, e.g. inform the user.

Upvotes: 0

TofuBeer
TofuBeer

Reputation: 61526

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.

Upvotes: 1

Bozho
Bozho

Reputation: 597036

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)

Upvotes: 0

JuanZe
JuanZe

Reputation: 8157

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 :)

Upvotes: 2

Related Questions