What Are Java Throw Exceptions?

Danielle Ellis
Danielle Ellis

Published:

Your credit card has a limit, and if you spend over that, your purchase may be declined. This concept of exceeding limits to receive a negative response is not specific to just credit cards--in Java, many things can be accepted or denied based on specific requirements.

Person learning how to throw java exception

Download Now: An Introduction to Java & JavaScript

For instance,  when a Java method attempts to perform an action that is not valid, we say that it "throws an exception." This article will focus on how to throw an exception in Java. We'll also look at some different types of exceptions, how to catch them, and how to create your custom exception.

So whether you're trying to figure out how to throw an exception in Java or want to learn more about how Java exception handling works, this article is for you.

What Is a Java Throw Exception

In Java, exceptions are objects that represent an error. It occurs during the execution of a program and disrupts the normal flow of instructions. When a program encounters an exceptional circumstance, an exception is "thrown." Depending on how your program is written, this exception may be caught and dealt with, or it may cause the program to crash.

When an exception occurs, the Java runtime system (JVM) automatically creates an object that contains information about the error. This object is then passed up the call stack until it is handled by some code. The program will terminate if no code catches the exception and outputs an error message.

Exceptions vs. Errors

It's important to note that two types of problems can occur in a Java program: exceptions and errors. Exceptions are (mostly) recoverable, while errors are not.

Errors are typically caused by problems out of your control, such as hardware failures or running out of memory. Because errors cannot recover from them, they will always cause a program to terminate. Exceptions, on the other hand, indicate conditions that the application might be able to recover.

For example, it is an exception if you have a file that your program is trying to read that cannot be found. Your program can catch this exception and prompt the user for a new file name. However, if your program tries to read from a file that does not exist, that would cause an error--there's nothing your program can do to recover.

Now that we've discussed the difference between exceptions and errors let's look at how to throw an exception in Java.

How to Throw An Exception in Java

There are two ways to throw an exception in Java: with the "throw" keyword or by creating a new instance of the Exception class.

We'll start by looking at how to throw an exception with the "throw" keyword. To do this, you'll need to create a new instance of the Exception class and then pass it to the "throw" keyword.

The syntax to throw an exception is below.

throw new Exception("Exception message");

Using the syntax, let's say we have a method that calculates the average of three numbers. However, we want to throw an exception if any numbers are less than 0. The method would look like this:

public static double average(double a, double b, double c) { if (a < 0 || b < 0 || c < 0) { throw new IllegalArgumentException("Can't have negative numbers"); } return (a + b + c) / 3.0; }

In this example, we're using the "throw" keyword to throw an IllegalArgumentException. The JVM will catch this exception, and an error message will be outputted. We can throw either a checked or unchecked exception, which we will discuss later.

Custom Exceptions

In addition to the built-in exceptions in Java, you can also create your own custom exceptions. Creating custom exceptions allows you to provide more informative error messages to your users.

You can create a custom exception by extending the Exception class. For example, let's say we want to create a custom exception for invalid input. The exception might look like this:

public class InvalidInputException extends Exception {    public InvalidInputException(String message) {        super(message);    } }

In the example above, the parent class is Exception. This class provides basic functionality for all exceptions. The InvalidInputException class is a child of Exception and provides a specific implementation for invalid input.  

Now, we can use our custom exception just like a built-in exception. The code to throw our InvalidInputException would look like this:

throw new InvalidInputException("Invalid input");

The code above will create a new exception with the following message: "Invalid input."

Now that we know how to throw exceptions, let's look at how to catch them.

How to Catch An Exception in Java

When an exception is thrown, the Java runtime system automatically creates an object containing information about the error. This object is then passed up the call stack until some code handles it.

The program will terminate if no code catches the exception and outputs an error message. However, if you catch the exception, you can deal with it somehow and then continue running your program.

You use the "try" and "catch" keywords to catch an exception in Java. The "try" keyword indicates a code section where an exception might occur. The "catch" keyword catches the exception and deals with it.

Take a look at the following example:

try { //Code goes here } catch (IOException e) { //Handle the exception }

In this code, the "try" block contains code that might throw an IOException. If an IOException occurs, it will be caught by the "catch" block, which will handle it somehow.

Note: You can have multiple "catch" blocks for a single "try" block. This is useful if you want to catch different types of exceptions differently. For example:

try {    //Code goes here } catch (IOException e) {    //Handle the IOException } catch (CustomException e) {    //Handle the CustomException }

In this code, there are two "catch" blocks. The first "catch" block catches IOExceptions, and the second "catch" block catches CustomExceptions. If an IOException occurs, it will be handled by the first "catch" block, and if a CustomException occurs, it will be handled by the second "catch" block.

You can also have a "finally" block in addition to the "try" and "catch" blocks. The "finally" block will always execute, regardless of whether or not an exception is thrown. For example:

try { //Code goes here } catch (IOException e) { //Handle the IOException } catch (CustomException e) { //Handle the CustomException } finally { //Execute this code no matter what }

In this code, the "finally" block will execute whether or not an exception is thrown. This can be useful for cleanup tasks, such as closing files or database connections.

Now that we've seen how to throw and catch exceptions, let's look at the difference between a checked and unchecked exception.

Types of Exceptions in Java

There are two exceptions in Java: checked and unchecked. Let's take a look at the difference between these types of exceptions.

Checked Exceptions

Checked exceptions occur at compile time and are checked by the compiler. If the compiler doesn't catch the exception, the program will not compile.  

Checked exceptions must either be caught or declared in the method where they occur.  The compiler will look for the "try," "catch," or "throws" keywords to handle a checked exception.

If we have a method that opens a file, but the file doesn't exist, a checked exception will be thrown. Take a look at the following example.

try {    FileReader file = new FileReader("doesntexist.txt"); } catch (FileNotFoundException e) {    System.err.println("File not found"); }

In the example above, we're using a try-catch block to catch the FileNotFoundException. The "try" block contains the code that may throw the exception. The "catch" block contains the code that will execute if the exception is thrown. The code in the catch block will not be executed if the file is found.

Catch exceptions are caused by user input or problems that occur within the code (like NullPointerException).

Examples of checked exceptions include:

  • IOException -  Thrown when an input or output operation is failed or interrupted.
  • ClassNotFoundException -  Thrown when an attempt is made to load a class through its string name, but no definition for the class could be found.
  • SQLException -  Thrown when a database access error occurs, or the connection to the database is lost.

Unchecked Exceptions

Unchecked exceptions occur at runtime and are not checked by the compiler. These exceptions are typically caused by programming bugs, improper use of APIs, or logic errors.

For example, if we try to divide a number by 0. Unlike checked exceptions, you don't need to catch or declare unchecked exceptions. However, it is considered best practice to do so.

Here is how you would catch an unchecked exception:

try { int result = num / 0; } catch (ArithmeticException e) { System.err.println("Can't divide by zero"); }

In the example above, we're trying to divide a number by 0, which will throw an ArithmeticException. We use a try-catch block to catch this exception and print an error message.

Examples of unchecked exceptions include:

  • NullPointerException - This exception occurs when you try to access a member of a null object.
  • IllegalArgumentException - This exception occurs when you pass an illegal argument to a method.
  • IndexOutOfBoundsException - This exception occurs when you try to access an element of an array or collection with an index that is out of bounds.

As you can see, there are two types of exceptions in Java: checked and unchecked. Checked exceptions must either be caught or declared, while unchecked exceptions do not need to be. However, it is best practice to catch or declare all exceptions.

Further Your Understanding of Java Throw Exceptions 

Since errors can happen in any program--no matter how well written--it's important to know how to deal with exceptions when they occur. Exceptions allow you to write more robust code that can handle unexpected situations gracefully rather than crashing.

By throwing an exception, we can tell the Java runtime system that something went wrong and that we need it to take some specific action. In this article, we've covered how to throw an exception and how to catch them. You can further your understanding of how to use exceptions by exploring some of the Java built-in exception classes or creating your own custom exceptions.

java

Topics: Java

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Learn more about the differences between and uses of these popular programming languages.