Sitemap
Lakshini Kuganandamurthy

Lakshini Kuganandamurthy

A passionate individual eager to learn and improve. Associate Software Engineer, Virtusa.

Exceptions

7 min readMay 30, 2022

--

Exceptions 😅 is n’t an easy topic as we think!!! There are minute points that need to be remembered 😄 Let’s dig in and ace them 👍

Runtime Exceptions

Runtime exceptions extend RuntimeException. They don’t have to be handled or declared. They can be thrown by the programmer or by the JVM.

Common runtime exceptions include the following:

  1. ArithmeticException — Thrown by the JVM when code attempts to divide by zero.
  2. ArrayIndexOutOfBoundsException — Thrown by the JVM when code uses an illegal index to access an array.
  3. ClassCastException — Thrown by the JVM when an attempt is made to cast an exception to a subclass of which it is not an instance.
  4. IllegalArgumentException — Thrown by the programmer to indicate that a method has been passed an illegal or inappropriate argument.
  5. NullPointerException — Thrown by the JVM when there is a null reference where an object is required.
  6. NumberFormatException — Thrown by the programmer when an attempt is made to convert a string to a numeric type but the string doesn’t have an appropriate format.

Checked Exceptions

Checked exceptions have Exception in their hierarchy but not RuntimeException. They must be handled or declared. They can be thrown by the programmer or by the JVM. Following are the common checked exceptions:

  1. FileNotFoundException — Thrown programmatically when code tries to reference a file that does not exist.
  2. IOException — Thrown programmatically when there’s a problem reading or writing a file.

For the OCA exam, you only need to know that these are checked exceptions. Note : FileNotFoundException is a subclass of IOException.

Errors

Errors extend the Error class. They are thrown by the JVM and should not be handled or declared. Following are some errors you may often see!!!

  1. ExceptionInInitializerError — Thrown by the JVM when a static initializer throws an exception and doesn’t handle it.
  2. StackOverflowError — Thrown by the JVM when a method calls itself too many times (this is called infinite recursion because the method typically calls itself without end).
  3. NoClassDefFoundError — Thrown by the JVM when a class that the code uses is available at compile time but not runtime.

❗️Points on each of the above.

ExceptionInitializerError

  • Java runs static initializers the first time a class is used.
  • If one of the static initializers throws an exception, Java can’t start using the class. It declares defeat by throwing an ExceptionInInitializerError.
static {
int[] countsOfMoose = new int[3];
int num = countsOfMoose[-1];
}
public static void main(String[] args) { }

This code outputs two exceptions:

Exception in thread “main” java.lang.ExceptionInInitializerError Caused by: java.lang.ArrayIndexOutOfBoundsException: -1

We get the ExceptionInInitializerError because the error happened in a static initializer. The ExceptionInInitializerError is an error because Java failed to load the whole class. Java also tells us the original cause of the problem, which is the ArrayIndexOutOfBoundsException that we need to fix.

StackOverflowError

  • When Java calls methods, it puts parameters and local variables on the stack.
  • After doing this a very large number of times, the stack runs out of room and overflows. This is called Stack overflowing and throws a StackOverflowError. Mostly, this error occurs when a method calls itself, as shown below.
public static void doNotCodeThis(int num) {
doNotCodeThis(1); //recursive calls
}

This outputs Exception in thread “main” java.lang.StackOverflowError.

Since the method calls itself, it will never end. Eventually, Java runs out of room on the stack and throws the error. This is called infinite recursion.

Note: It is better than an infinite loop because at least Java will catch it and throw the error. With an infinite loop, Java just uses all your CPU until you can kill it.

NoClassDefFoundError

  • NoClassDefFoundError occurs when Java can’t find the class at runtime.
  • This error won’t show up in code on the OCA exam, you just need to know that it is an error.

Calling methods that throw exceptions

  • When you’re calling a method that throws an exception, the rules are the same as within a method. Why does the following code not compile???
class NoMoreCarrotsException extends Exception {}public class Bunny {
public static void main(String[] args) {
eatCarrot();// DOES NOT COMPILE
}
private static void eatCarrot() throws NoMoreCarrotsException {}
}

The problem is that NoMoreCarrotsException is a checked exception. Checked exceptions must be handled or declared. This will compile if you do the following changes:

  1. Declare the exception for the main method as shown below. Here, eatCarrot() didn’t actually throw an exception; it just declared that it could throw an exception.
public static void main(String[] args) throws NoMoreCarrotsException {// declare exception
eatCarrot();
}

2. Handle the exception using try-catch block as shown below.

public static void main(String[] args) {
try {
eatCarrot();
} catch (NoMoreCarrotsException e ) {// handle exception
System.out.print("sad rabbit");
}
}

The compiler is still on the lookout for unreachable code. Declaring an unused exception isn’t considered unreachable code. It gives the method the option to change the implementation to throw that exception in the future.

Subclasses

In this section, we’ll be looking at overriding methods with exceptions in the method declaration.

Get Lakshini Kuganandamurthy’s stories in your inbox

Join Medium for free to get updates from this writer.

When a class overrides a method from a superclass or implements a method from an interface, it’s not allowed to add new checked exceptions to the method signature. Consider the below e.g.

class CanNotHopException extends Exception { }class Hopper {
public void hop() { }
}
class Bunny extends Hopper {
public void hop() throws CanNotHopException { } // DOES NOT //COMPILE
}

Java knows hop() isn’t allowed to throw any checked exceptions because the superclass Hopper doesn’t declare any. Therefore when we override the hop() method in the Bunny class, by adding a checked exception, compiler throws a compile error.

  • A subclass is allowed to declare fewer exceptions than the superclass or interface. This is legal because callers are already handling them.
  • A subclass not declaring an exception, is similar to a method declaring it throws an exception that it never actually throws.
  • Similarly, a class is allowed, to declare a subclass of an exception type.

Look at the below e.g.

class Hopper {
public void hop() throws Exception { }
}
class Bunny extends Hopper {
public void hop() throws CanNotHopException { }
}
  • Bunny could declare that it throws Exception directly or it could declare that it throws a more specific type of Exception. It could even declare that it throws nothing at all.

❗️ ❗️ ❗️This rule applies only to checked exceptions.

The following code is legal because it has a runtime exception in the subclass’s version.

class Hopper {
public void hop() { }
}
class Bunny extends Hopper {
public void hop() throws IllegalStateException { }
}

The reason that it’s okay to declare new runtime exceptions in a subclass method is that the declaration is redundant. Methods are free to throw any runtime exceptions they want without mentioning them in the method declaration.

Printing an Exception

There are three ways to print an exception.

  1. You can let Java print it out.
  2. Print just the message.
  3. Print where the stack trace comes from.

Check the below e.g.

public static void main(String[] args) {
try {
hop();
} catch (Exception e) {
System.out.println(e);
System.out.println(e.getMessage());
e.printStackTrace();
}
}
private static void hop() {
throw new RuntimeException("cannot hop");
}
/*
The above code gives the following output:
java.lang.RuntimeException: cannot hop
cannot hop
java.lang.RuntimeException: cannot hop
at trycatch.Handling.hop(Handling.java:15)
at trycatch.Handling.main(Handling.java:7)
*/

The first line shows what Java prints out by default: the exception type and message. The second line shows just the message. The rest shows a stack trace. The stack trace is usually the most helpful one because it shows where the exception occurred in each method that it passed through.

On the OCA exam, you will mostly see the first approach.

The stack trace shows all the methods on the stack. Every time you call a method, Java adds it to the stack until it completes. When an exception is thrown, it goes through the stack until it finds a method that can handle it or it runs out of stack.

Summary

  • An exception indicates something unexpected happened.
  • A method can handle an exception by catching it or declaring it for the caller to deal with.
  • Many exceptions are thrown by Java libraries.
  • You can throw your own exception with code such as

throw new Exception().

  • Subclasses of java.lang.Error are exceptions that a programmer should not attempt to handle.
  • Subclasses of java.lang.RuntimeException are runtime (unchecked) exceptions.
  • Subclasses of java.lang.Exception, but not java.lang.RuntimeException are checked exceptions.
  • Java requires checked exceptions to be handled or declared.
  • If a try statement has multiple catch blocks, at most one catch block can run.
  • Java looks for an exception that can be caught by each catch block in the order they appear, and the first match is run. Then execution continues after the try statement.
  • If both catch and finally throw an exception, the one from finally gets thrown.
  • The common runtime exceptions include:
  1. ArithmeticException
  2. ArrayIndexOutOfBoundsException
  3. ClassCastException
  4. IllegalArgumentException
  5. NullPointerException
  6. NumberFormatException

IllegalArgumentException and NumberFormatException are typically thrown by the programmer, whereas the others are typically thrown by the JVM.

  • Common checked exceptions include:
  1. IOException
  2. FileNotFoundException
  • Common errors include:
  1. ExceptionInInitializerError
  2. StackOverflowError
  3. NoClassDefFoundError
  • When a method overrides a method in a superclass or interface, it is not allowed to add checked exceptions. It is allowed to declare fewer exceptions or declare a subclass of a declared exception. Methods declare exceptions with the keyword throws.

Exam Essentials

💡 Unchecked exceptions are also known as runtime exceptions and are subclasses of java.lang.RuntimeException.

💡 All other subclasses of java.lang.Exception are checked exceptions.

💡 A try statement must have a catch or a finally block.

💡 Multiple catch blocks are also allowed, provided no superclass exception type appears in an earlier catch block than its subclass.

💡 The finally block runs last regardless of whether an exception is thrown.

💡 IllegalArgumentException and NumberFormatException are commonly thrown by the programmer. Most of the other runtime exceptions are typically thrown by the JVM.

💡 The throws keyword is used in a method declaration to indicate an exception might be thrown.

💡 When overriding a method, the method is allowed to throw fewer exceptions than the original version.

💡 The throw keyword is used when you actually want to throw an exception.

💡 The throws keyword is used in a method declaration.

Hope this article is useful!!! 😃

Happy Learning!!!

--

--

Lakshini Kuganandamurthy
Lakshini Kuganandamurthy