Exceptions & AssertionsJ8 Home « Exceptions & Assertions

  • Exceptions and Assertions
    1. Use try-catch and throw statements.
    2. Use catch, multi-catch, and finally clauses.
    3. Use Autoclose resources with a try-with-resources statement.
    4. Create custom exceptions and Auto-closeable resources.
    5. Test invariants by using assertions.

The table below breaks the above list down into topics with a link to the topic in question.

topic Link
Use try-catch and throw statements.
Use catch, multi-catch, and finally clauses.
Use Autoclose resources with a try-with-resources statement.
Create custom exceptions and Auto-closeable resources.
Test invariants by using assertions.Using the assert Keyword
Appropriate Assertion Usage

try catch finally  ConstructTop

The following table shows the different forms of the try catch finally construct.

Construct Description
try catch
try {
    // Code to be monitored for exception goes here
}
catch (Exception ex) {
    // Code to be executed on exception
}

Execute statements in try code block.


Execute statements in catch code block.
try catch finally
try {
    // Code to be monitored for exception goes here
}
catch (Exception ex) {
    // Code to be executed on exception
}
finally () {
    // Code to be run whether exception or not
}

Execute statements in try code block.


Execute statements in catch code block


Execute statements in finally code block.
try finally
try {
    // Code to be monitored for exception goes here
}
finally () {
    // Code to be run whether exception or not
}

Execute statements in try code block.


Execute statements in finally code block.
try with multiple catch
try {
    // Code to be monitored for exception goes here
}
catch (Exception1 ex1) {
    // Code to be executed on exception 1
}
catch (Exception2 ex2) {
    // Code to be executed on exception 2
}
...
catch (ExceptionN exN) {
    // Code to be executed on exception N
}

Execute statements in try code block.


Execute statements in catch code block 1.


Execute statements in catch code block 2.



Execute statements in catch code block N.
try with multiple catch and a finally
try {
    // Code to be monitored for exception goes here
}
catch (Exception1 ex1) {
    // Code to be executed on exception 1
}
catch (Exception2 ex2) {
    // Code to be executed on exception 2
}
...
catch (ExceptionN exN) {
    // Code to be executed on exception N
}
finally () {
    // Code to be run whether exception or not
}

Execute statements in try code block.


Execute statements in catch code block 1.


Execute statements in catch code block 2.



Execute statements in catch code block N.


Execute statements in finally code block.

try catch finally  Rules

When using the try catch finally construct there are certain rules that must be adhered to or you get a compiler error:

  • When using a try block it must be accompanied by a catch block, a finally block or both.
  • When using a catch block it must immediately follow the try block.
  • When using multiple catch blocks they must go in order from the most specific error to the most generic as discussed in Exceptions And Polymorphism.
  • When using a finally block it must immediately follow the last catch block, or the try block when no catch block is present.

Declaring ExceptionsTop

We can use the throw   keyword to throw exceptional conditions from within our code. At the top of the exception hierarchy is the Throwable class, which all other error and exception classes inherit from. So we can throw any subtype of the Throwable class if we want to, which includes objects of type Error, Exception and RuntimeException. The compiler demands that we either handle or declare exceptions which are neither error or runtime exceptions, in other words checked exceptions. See the Declaring Exceptions lesson for example usage.

Overridden Methods & Exceptions

There are a few things to remember when overriding methods that throw exceptions:

  • An overriding method can throw any Error or RuntimeException exceptions, whether these are declared in the overridden method or not.
  • An overriding method must not throw any new checked exceptions or any checked exceptions that are higher up the inheritance tree than those declared in the overridden method.
  • An overriding method can throw checked exceptions that are lower in the inheritance tree than those declared in the overridden method, or throw fewer or none of the checked exceptions that were declared in the overridden method.

Certification Exceptions & ErrorsTop

The following table lists the exceptions and errors we need to know for the certification:

Error/Exception Description
ArrayIndexOutOfBoundsExceptionAttempt to access array with an illegal index.
An example of this exception is shown in the Arrays lesson when we look at java.lang Array Exceptions.
ClassCastExceptionAttempt to cast an object to a subclass of which it is not an instance.
An example of this exception is shown in the Generics lesson when we look at a Raw Type/Generic Type Comparison.
IllegalArgumentExceptionMethod invoked with an illegal argument.
IllegalStateExceptionMethod invoked while an application isn't in the correct state to receive it.
NullPointerExceptionAttempt to access an object with a null reference.
An example of this exception is shown in the Reference Variables lesson when we look at The Heap.
NumberFormatExceptionInvalid attempt to convert the contents of a string to a numeric format.
An example of this exception is shown in the Exception Handling lesson when we look at Using  try catch finally.
AssertionErrorAssertion boolean test returns false.
An example of this exception is shown in the Using Assertions lesson when we look at Using the assert Keyword.
ExceptionInInitializerErrorAn unexpected exception has occurred in a static initializer.
StackOverflowError A stack overflow occurs because an application recurses too deeply.
NoClassDefFoundErrorTry to load in a class that can no longer be found.

Using the assert KeywordTop

The following table shows the two forms of the assert statement which are only active when running our code with the -ea option. The second form just allows us to pass more information to an AssertionError and we must ensure that the expression returns a value.

Assert Form Example Description
form1
assert condition;

// Other code
assert (a > 0);Throw AssertionError if condition equates to false

Run this code when assertion equates to true.
form2
assert condition: expression;


// Other code
assert (a > 0): "a = " + a;Throw AssertionError if condition equates to false passing the value returned from expression.

Run this code when assertion equates to true.

Appropriate Assertion UsageTop

Assertions should not be used to validate command-line arguments. We would have to run the code everytime using the -ea option to ensure assertions run the validation. Using exceptions is more appropriate for validating command-line arguments as these run regardless of deployment and the use of the -ea option.

Assertions should never be used that cause side-effects such as changing a value used elsewhere in the code. If we do so we are reliant on code being run using the -ea option to get the values changed. What happens when someone else runs the code without assertions enabled! Unreliable results are a difficult bug to find, that isn't really a bug, just an incorrect use of the assertion mechanism.

When considering whether to use assertions to validate arguments to a method, we need to consider the access modifier of the method:

  • Methods marked as public are not considered appropriate for assertions; public methods are available to anyone and should be robust enough to guarantee the validation and robustness of their interfaces. Using exceptions is more appropriate for public methods as these run regardless of deployment and the use of the -ea option.
  • Methods marked as protected are not considered appropriate for assertions; protected methods are available to subclasses outside the package and so should be robust enough to guarantee the validation and robustness of their interfaces. Using exceptions is more appropriate for protected methods as these run regardless of deployment and the use of the -ea option.
  • Methods with no access modifier are appropriate for assertions if you control the package; package-private methods are available only to programs within the package they belong to. If you have control then you can be reasonably assured that logic calling your protected method is correct.
  • Methods marked as private are considered appropriate for assertions as you control the code that calls the method; private methods are available only to the class they are written in. Therefore you have control and can be reasonably assured that logic calling your private method is correct.

Assertions should be used anywhere in code when you have code that should never be reached, such as a switch default statement, that you know will never be invoked. In these situations you set the assertion mechanism to false rather than test a condition. This ensures that if the statement is ever reached, when assertions are enabled, we will get an AssertionError.

See the Flow Control - Using Assertions lesson for example usage.

Related Java Tutorials

Fundamentals - Conditional Statements
Fundamentals - Loop Statements
Fundamentals - Primitive Variables
Fundamentals - Operators
Flow Control - Using Assertions
Flow Control - Exception Overview
Flow Control - Exception Handling
Flow Control - Declaring Exceptions