Skip to main content

Java For Python Programmers Edition 2

Section 4.5 Exception Handling

In Python, if you want a program to continue running when an error has occurred, you can use try-except blocks to handle exceptions. If you wanted to write a program that asks the user to enter a whole number and then squares that number, you could use the following code to do so:
The Java code that would perform the same task is a little more complex and utilizes the Scanner class for input.
This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add try-except (Python) or try-catch (Java) blocks within a while loop that iterates until the user enter the correct code. Adding try-except blocks and a while loop to the Python code will look something like this:
Now that we have Python code that will continuously prompt the user until they enter a whole number, letโ€™s look at Java code that accomplishes the same task. Like most other equivalent Java code blocks, this code has a lot of extra bits that are necessary to get working code.
Firstly, letโ€™s talk about the extra import alongside the Scanner import. In Java, we need to import InputMismatchException because itโ€™s not automatically available like basic exceptions. This is different from Python where most exceptions are readily accessible. If you ran the previous Java codeblock without try-catch blocks and entered an erroneous input, you would have got an InputMismatchException exception despite not having imported this class. That being said, removing the explicit import of this library for the try-catch code block above will lead to compilation errors.
Exceptions in Java fall under two categories: checked and unchecked. Checked exceptions must be explicitly imported and declared along with try-catch blocks for a program to compile. Unchecked exceptions do not need to be imported unless try-catch blocks are implemented for them (except for java.lang exceptions). InputMismatchException is an unchecked exception that is not part of the java.lang library, so it is only included if try-catch blocks declare it. Here are some common exceptions used with try-catch blocks:
Table 4.5.1. Exceptions
Exception Package Description
IOException java.io Thrown when an I/O operation fails (e.g., reading or writing a file).
FileNotFoundException java.io Thrown when an attempt to open a file denoted by a pathname has failed.
ParseException java.text Thrown when parsing a string into a date, number, etc. fails (e.g., wrong format).
NoSuchMethodException java.lang Thrown when a particular method cannot be found via reflection.
InputMismatchException java.util Thrown when Scanner input doesnโ€™t match the expected data type.
SQLException java.sql Thrown when a database access error occurs (e.g., invalid SQL query, bad connection).
InstantiationException java.lang Thrown when trying to create an instance of an abstract class or interface.
IllegalAccessException java.lang Thrown when a reflection operation tries to access a field or method it doesnโ€™t have permission for.
Note that as with other structures in Java, try-catch blocks blocks must be encased with braces {}. The most important part of this code is, after catch, there is a set of parenthesis with an exception type and a variable name catch (InputMismatchException e). This is where we declare a InputMismatchException exception and name it with the variable name e. It is common practice, though not a requirement, to name exception variables e in this manner.
You have attempted of activities on this page.