Home

 › 

Articles

 › 

What is Exception Handling in Java, with Examples?

OpenCL vs CUDA

What is Exception Handling in Java, with Examples?

In Java, exceptions are extraordinary or unexpected events that take place during the execution of a software program. When an exception, or error occurs during the execution of a script, Java usually responds by terminating the program and throwing out an error message. However, exception handling in Java can help you deftly manage the common runtime errors so your application can continue to function.

In this article, we explain what exception handling in Java is, with examples to keep your programs running. Let’s get started!

What is an Exception in Java?

Exceptions are simply unexpected events that turn up while a Java program is being executed. The problem with exceptions is that they abruptly intersect the normal execution of the program.  If they are unaccounted for in the Java code, and don’t have a workaround, Java will pause execution or terminate the program and generate an error message. Understandably, this is a hassle and can make working in Java complicated until you know how to deal with it. 

What Causes Exceptions in Java?

Lots of things can cause an exception in Java, but here are the common causes:

  • A loss of network connectivity: Internet connectivity is not established before the program attempts to execute.
  • Device problems including device failure or device type mismatch error.
  • Not enough disk memory: Java throws up an exception if a drive is full or has inadequate space. Attempts to open an unavailable file have a similar effect.
  • Invalid user input: Invalid user inputs are a common Java exception or error.
  • Code errors: A runtime error can alert a developer to errors in their code.

Java Exception Types and Hierarchy

Java exceptions can be divided into two major classes depending on whether they occur during compile time (when programming code is transitioned to machine code) or runtime (when the program is running).

  1. IOExceptions or checked exceptions occur during the compile time. The compiler will check the code and alert the developer to exceptions like FileNotFoundException.
  2. RuntimeException or unchecked exception occurs during the execution of a program and are almost always due to a programming error and includes exceptions like NullPointerException or IllegalArgumentException.

Exceptions are also organized hierarchically in Java, with the throwable class as the root class. Beneath the root class here are errors that are basically irrecoverable situations like no memory or stack overflow, and exceptions that are things a programmer can deal with through exception handling. 

Javascript code
Exceptions occur in Java (no pun intended), and there are some simple methods that can be used to handle them.

So, What is Exception Handling in Java?

In Java and other programming languages, exception handling refers to the methods or processes a developer can use to respond to the occurrence of exceptions during the routine operation of a program. 

By using exception handling, devs can avoid their programs from being disrupted or crashing, safeguarding the normal function as intended by the code. This is not only important for the professional performance developer but also for the user, who could lose important data if a program they are working on suddenly crashes! 

Remember that exception handling only applies to runtime exceptions and not errors that cannot be rectified by code. 

Exception handling in Java has its own constructs and well-known snippets that can be used to interrupt the default pause in the program, prevent Java from throwing up an error message, and utilize other resources or processes to “handle” the exception. 

Java Exception Handling Examples 

If you are new to Java, it is best to start by mastering the simplest exception-handling methods, before attempting to solve more complex problems.

Below are the two most common examples.

Example #1: try-catch (+finally)

This is the most basic exception-handling method available in Java. It is satisfying to perform because it will catch just about any exception that Java throws at you. You can place code you want to run in the try block and the exceptions that are thrown up will be caught by the catch block. 

The only caveat is that you cannot use an unpaired try block. Always ensure that you follow the try block with a catch block and follow with a “finally” block that ensures that your code continues to be executed as intended whether an exception is caught or not.

This helpful video shows you the try-catch method in action:

Example #2: UncaughtExceptionHandler

This is an exception-handling method that you can use to deal with unexpected runtime exceptions, where you do not have a try-catch block in place. You can set an UncaughtExceptionHandler on any thread. It will be invoked if the thread is about to be terminated by an uncaught exception.

Here is how to use the UncaughtExceptionHandler:

Wrapping Up

Even the cleanest code can be affected by exceptions, so it’s important to have some tools for dealing with them when they inevitably occur. Try-catch is a great preemptive maneuver for tackling run-time exceptions, and if an uncaught exception crops up, you can tackle it by attaching UncaughtExceptionHandler to the thread. 

Frequently Asked Questions

What is Java Virtual Machine?

Java Virtual Machine (JVM) is the virtual machine that enables Java to run its programs on any computer. It is responsible for the loading, verification, and execution of Java bytecode, an instruction set that interfaces with the computer so that a Java program can be run.

What is exception tracking in Java?

Exception tracking is the recording of all exceptions that occur on the log file of the software application. If all events are recorded, developers can review the log file and see what led to the occurrence of the exception. Exception tracking is important because the runtime environment may be unpredictable, especially from the user end, so unexpected exceptions inevitably occur.

How can you check internet connectivity using Java?

You can check the internet connection in Java using:

  • Java Runtime class
  • getRuntime() method
  • URLConnection class

 

What is multiple exceptions in Java?

Multiple exceptions is where Java catch blocks can handle more than one type of exception. This is useful as it keeps the code clean (fewer duplications) and prevents the exceptions caught from having to be overly broad.  This is available in Java 7 and more recent versions. 

What is the most common Java exception?

NullPointerException is an unchecked exception that occurs when an object is processed that has a null value, and it’s the most common exception in Java.

To top