What is a Java exception? For starters, it's often a major stressor for developers causing grey hairs and broken keyboards. But it doesn’t have to be that way, and in this post, you will learn how to handle Java exceptions with ease and confidence.This post will cover the different types of Java exceptions and how you can handle them to improve your software production. You will also learn the following concepts to improve your development process:
- What is an exception in Java?
- What are the two types of native Java exceptions?
- What a User Defined Java Exception is
Without further delay, let’s dive right in.
What is an exception in Java?
The term “exception” in Java may sound confusing, but truthfully it's just a term Java uses to name any behavior that does not fit expectations. Exceptions in Java are used to track and identify anything that is an exception to the expected behavior of a given software.
All software has parameters they need to operate within; when the software runs outside of those parameters, developers need a way to track it. In Java, these exceptions get tracked using a superclass called the throwable class. Java classes are used to create organization and help with coding efficiency, including unexpected behavior and expected behavior that is undesirable.
Good programming practices call for a way to monitor, track and respond to events of all types. In the case of exceptional events, Java gives us the throwable class, which allows us two other exception classes. With that in mind, it’s essential to understand that Java exceptions differ from errors, and Java offers a class based on throwable to handle errors too – surprise, surprise, it's called the error class.
Before we go any further, let’s briefly discuss the difference between the two types of Java throwables. Java errors occur within the operating environment, while Java exceptions are raised by the software code itself.
Now that we’ve discussed that, let’s move on to the two types of exceptions that can occur with your Java Software.
What are the two types of native Java exceptions?
Let’s start by acknowledging that any Java exception thrown is an object; this is important because it means that any exception can have several properties. Each property helps with the efficacy of tracking throwable events during operation, which can help identify the exception and its cause.Furthermore, it can help with identifying a potential solution to it as well. Java has split the throwable exceptions into two classes to further aid in these important processes. The throwable exception classes are called Unchecked exceptions and checked exceptions. Check out the image below to learn more about the difference between the two types of exceptions.Let’s look at those next.
Common Unchecked Exceptions in Java
Before we look at some examples of common unchecked exceptions, let's discuss what an unchecked exception is.An unchecked exception sounds like something you might freak out about, but it's not that scary. An unchecked exception is an exception that occurred but cannot be recovered. The simple definition is an exception that happened quickly and then passed. But the exception was not handled and does not interfere with runtime operations. The idea is that the software will run whether you handle the exception or not. Do not misunderstand, though. While it won't interfere with runtime operations, it can still cause undesired behavior in your software. Always track and handle any exceptions you may encounter.
RuntimeException: This is a superclass that encompasses all unchecked exceptions.
NullPointerException: This exception gets thrown when a null value is encountered where an object should be.
ArithmeticException: These exceptions get thrown in response to a failed arithmetic operation.
ArrayIndexOutOfBoundsException: An exception gets thrown when an index is encountered outside the available array bounds. (i.e.… 5 item array, but the current index is 6)
IllegalArgumentException: Thrown when an argument is used that does not follow the given rules of the software. (Such as providing a string argument where an integer is expected.)
IllegalStateException: An exception gets thrown when the current state does not follow the expectations of the software. (Such as a state that expects a number value but gets a string instead)
ConcurrentModificationException: An exception thrown in response to a collection changing during iteration, such as a user changing an input value.
Common Checked Exceptions in Java
By now, you’ve probably guessed what a checked exception is; it’s an exception that MUST be handled or declared. These exceptions can cause major issues with the operation of your software during compilation and, therefore, can prevent your software from running in its target environment.
IOException: This exception gets thrown on a failed input or output operation.
SQLException: An exception thrown in response to a failed database operation.
ClassNotFoundException: This exception gets thrown in response to a referenced class that Java cannot find.
InstantiationException: This exception gets thrown when an object instantiation fails. (Such as when insufficient information is provided for said object.)
NoSuchMethodException: If a method is used and Java Cannot find the method, this error gets thrown in response.
All exceptions should be identified and handled in one way or another to avoid erroneous behavior within your software. Thankfully Java makes this easy for us to do. Furthermore, not all erroneous behavior can be caught by Java. Java gives us another way to catch issues not wanted in the software by allowing developers to identify and define specific exceptions that could cause problems.
User-Defined Java Exceptions
A user-defined exception is an exception the developers define to catch issues that Java may not know to catch. A great example of this is capturing invalid user input or even erroneous user input. This ability to create exceptions helps further improve the development process by simplifying the process of preventing undesired behavior within the software.
Moreover, there will be software-specific exceptions that developers want to catch in order to improve the user experience. These exceptions may not interfere with the overall function of the software but may impact the experience in aesthetic ways. Watch the video below to learn more about defining custom user-defined exceptions.
Exception Example In Java
With all of that explained, let’s look at an example of an exception object and see how the properties of the object may help you track down where the exception took place and how to fix it. It is important to note that not all exceptions come with built-in properties, only exceptions that fall under the runtime umbrella come with built-in properties. An example of this is the java.sql.SQLException, which has the String SQLState and vendorCode properties. These properties help narrow down the cause of the exception using predefined information. This information is provided because Java is able to identify the exception and its cause.This means that unchecked exceptions will have properties that help identify the issue. But what about checked exceptions? In this case, catching the exception is essential as it allows adding properties that can provide more detailed information about them and help solve the problem. Let’s look at how to catch an exception and print out more detailed information about it.First, you start by forcing an exception that could occur using the try-catch block, as seen below.
This process allows you to specify the information provided to the exception object and display it on the screen as a helpful message. The video below provides more information on handling exceptions in your Java software code.
Dealing with Java Exceptions Moving Forward
Armed with the knowledge in this post, you are well on your way to being highly effective in dealing with Java exceptions. It can still be a lot to take in and retain over time; however, there are ways to solidify your knowledge on the subject.The best way, of course, is to start creating your own Java exceptions and learn how they work more intimately. By using try-catch blocks to handle your exceptions, you can familiarize yourself with the subject much better and improve your software development.