In the beginning of our course, we introduced software development as a process, where designing and implementing a program often is not sufficient for our software solution to work under all circumstances. In practice, depending on the machine and system properties where the software is deployed and the end users the software may encounter unforeseen problems. In this module, we introduce these exceptions to expected software behavior, and how they can be handled in our Java programs.
Exceptions
Let’s start our lecture by defining what exceptions are and how they are used in the Java programming language.
Exception handling
Exceptions are very common events during the execution of any software program and because of this, Java offers specialized syntax to declare the handling of exceptions. We can now introduce exception handling constructs and how they can be used to catch and handle different types of exceptions.
Writing your own Exception classes
In addition to the predefined set of exceptions in the Java library, we can also declare and use our own exceptions with specific properties and methods. The following video presents how we can extend exceptions in our own Java programs.
Exercises
Given the four types of programs that can raise runtime exceptions, implement exception handling with try-catch statements
The InputMismatchException might occur if the user enters an input that has an unexpected type or size
ArithmeticException refers to any failures in arithmetic computations, where an example can look like the following computation below:
ArrayIndexOutOfBoundsException is another type of exception that occurs when an invalid or nonexistent array index is attempted to be accessed.
Solutions
In each case, we can handle potential exceptions by surrounding the parts of the program in the main method that are prone to raising the exception with a try clause. Depending on the type of exception, we can write a specific catch clause for handling the given type of exception.
The try-catch block for handling exceptions of type InputMismatchException:
The try-catch block for handling exceptions of type ArithmeticException can also be written in the same way:
Similarly, the try-catch block for handling exceptions of type ArrayIndexOutOfBoundsException can look like this:
Please try to write your own try-catch blocks for each type of exception for practice and refer to the module quiz to assess your understanding.