Exceptions

Contact Us or call 1-877-932-8228
Exceptions

Exceptions

Exceptions are generated when a recognized condition, usually an error condition, occurs during the execution of a method. There are a number of standard error conditions defined in Java, and you may define your own error conditions as well.

When an exception is generated, it is said to be thrown.

Java syntax includes a system for managing exceptions, by tracking the potential for each method to throw specific exceptions. Note that:

  • For each method that could throw an exception, your code must inform the Java compiler that it could throw that specific exception.
  • The compiler marks that method as potentially throwing that exception, and then requires any code calling the method to handle the possible exception.

There are two ways to handle an exception:

  • You can try the "risky" code, catch the exception, and do something about it, after which the propagation of the exception ceases.
  • You can mark the method with the risky statement indcating that it throws an exception. Any statement that calls a method capable of throwing an exception must deal with it.

So, if you use a method in your code that is marked as throwing a particular exception, the compiler will not allow that code unless you handle the exception

Once an exception is thrown, it propagates backward up the chain of methods, from callees to callers, until it is caught. Note that:

  • If the exception occurs in a try block, the JVM looks to the catch block(s) that follow to see if any of them match the exception type.
  • The first one that matches will be executed.
  • If none match, then this method ends, and execution jumps to the method that called this one, at the point where the call was made.

If an exception is not caught in your code (which would happen if main was marked as throwing the exception) then the JVM will catch the exception, end that thread of execution, and print a stack trace.

There are cases where the compiler does not enforce these rules. Exceptions that fit this category are called unchecked exceptions.

Next