Day 43 (week 9) — Exceptions

Java is a compiled language. There are many implications that come from that statement, and today we learned about how to throw and catch exceptions. Let me give a straightforward example to illustrate.

Suppose that somewhere in your code you have two integers. It really doesn’t matter so much where they come from. What matters is that we might not know ahead of time what these two integers values would be. Your code needs to compute the quotient of these two integers, so you write something like this. I’m assigning these two integers the values of 2 and 0, but in a bigger program, their values might not be so well understood at runtime.

public static void main(String[] args) {
int a = 2;
int b = 0;

int c = a/b;

System.out.println(c);
}

This code compiles since there are no syntax errors. However, when you execute the program, it turns out that b is zero. From a mathematical perspective dividing by zero is not permitted. As a side note, I have a really good explanation about why this must be the case and perhaps I’ll go into more detail later. For now, the focus should be on how the computer handles division by zero. In Java, when this code runs, we get an error.

Exception in thread "main" java.lang.ArithmeticException: / by zero

Notice that the print statement after the division doesn’t run. Even if it did, what result would the computer be able to print? Since division by zero is not defined, the authors of the language decided that throwing an exception was the appropriate response.

Effectively, as the JVM executed this code, the a/b operation detected the error and threw an exception. When this happens, execution of the program stops. The exception is not caught anywhere in our code, so it is handed to the JVM, which prints the error message and the program exits.

It is often the case that our code might behave badly based on faulty inputs or something else we might not be able to anticipate. In these cases, exception handling provides us with a structure to gracefully handle the error and continue executing. Here’s what that looks like.

try {
int a = 2;
int b = 0;

int c = a/b;
}
catch(ArithmeticException e) {
System.out.println("An arithmetic error occurred");
}

System.out.println("This line will print, since program execution continues.");

And sure enough, if we look at the output.

An arithmetic error occurred
This line will print, since program execution continues.
Process finished with exit code 0

So, by catching, or handling the exception, our program can continue to execute even though we attempted to do something that generated an error.

Admittedly, exception handling is a much deeper topic that involves catching different types of exceptions, defining your own custom exceptions, throwing your own custom exceptions, and much more.

We also ran into another example of exception handling. This one I’m not so comfortable with. The idea is that you want to write code that reads from user input at the console and waits until we get a valid integer. We wrote a method called getSafeInt that looked like this.

public static int getSafeInt () {
// NumberFormatException thrown by parseInt
// and for an empty string
int newInt = 0;
try {
newInt = Integer.parseInt(
newScanner(System.in).nextLine());
} catch (NumberFormatException e) {
getSafeInt();
}

return newInt;
}

Notice what’s happening here. We read a line from the input stream and attempt to interpret that input as an integer using Integer.parseInt. If parseInt is unhappy with our input, it throws a NumberFormatException exception and in the catch block we simple call the function again. Effectively, we are telling the computer to wait for a valid integer.

I don’t know how happy I am with this. It seems more reasonable to have some sort of while loop that waits for a valid integer. Although this code works, it probably isn’t good practice. For example, what if the user never inputs a valid integer? We would just be stuck in this recursive exception path forever.

One last thing. I can’t help but feel like I’m fighting with Java as I write code. I’ve learned many other languages before like C, C++, Python, Perl, and Javascript. The IntelliJ IDE that we are working in is constantly trying to be helpful in suggesting what my code should look like. I’m not offended by this, but it is a little irritating.

I’m also finding that Java is different in that it is more difficult to express what I want the code to do. I understand that Java is compiled and statically-typed and that it makes for more robust and sometimes faster programs. It just feels like the language isn’t very cooperative.

Perhaps this is simply a sign that I don’t know enough about it and as I become more fluent in coding Java, the language will come more naturally. I’m hoping that is the case.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.