Exceptions & AssertionsJ8 Home « Exceptions & Assertions
- Exceptions and Assertions
- 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.
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 KeywordAppropriate Assertion Usage |
try catch finally ConstructTop
The following table shows the different forms of the try catch finally construct.
| Construct | Description |
|---|---|
try catch | |
try { |
Execute statements in try code block.Execute statements in catch code block. |
try catch finally | |
try { |
Execute statements in try code block.Execute statements in catch code blockExecute statements in finally code block. |
try finally | |
try { |
Execute statements in try code block.Execute statements in finally code block. |
try with multiple catch | |
try { |
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 { |
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
tryblock it must be accompanied by acatchblock, afinallyblock or both. - When using a
catchblock it must immediately follow thetryblock. - When using multiple
catchblocks they must go in order from the most specific error to the most generic as discussed in Exceptions And Polymorphism. - When using a
finallyblock it must immediately follow the lastcatchblock, or thetryblock when nocatchblock 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
ErrororRuntimeExceptionexceptions, 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 |
|---|---|
ArrayIndexOutOfBoundsException | Attempt 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. |
ClassCastException | Attempt 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. |
IllegalArgumentException | Method invoked with an illegal argument. |
IllegalStateException | Method invoked while an application isn't in the correct state to receive it. |
NullPointerException | Attempt 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. |
NumberFormatException | Invalid 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. |
AssertionError | Assertion boolean test returns false.An example of this exception is shown in the Using Assertions lesson when we look at Using the assert Keyword. |
ExceptionInInitializerError | An unexpected exception has occurred in a static initializer. |
StackOverflowError | A stack overflow occurs because an application recurses too deeply. |
NoClassDefFoundError | Try 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 falseRun 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
publicare not considered appropriate for assertions;publicmethods are available to anyone and should be robust enough to guarantee the validation and robustness of their interfaces. Using exceptions is more appropriate forpublicmethods as these run regardless of deployment and the use of the-eaoption. - Methods marked as
protectedare not considered appropriate for assertions;protectedmethods 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 forprotectedmethods as these run regardless of deployment and the use of the-eaoption. - Methods with no access modifier are appropriate for assertions if you control the package;
package-privatemethods are available only to programs within the package they belong to. If you have control then you can be reasonably assured that logic calling yourprotectedmethod is correct. - Methods marked as
privateare considered appropriate for assertions as you control the code that calls the method;privatemethods are available only to the class they are written in. Therefore you have control and can be reasonably assured that logic calling yourprivatemethod 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