In the software world, error occurring is common and this can happen due to various reasons- for example, a user input contains an error, an external system that does not respond, or simply a programming error. However, like most modern programming languages, Java offers advanced exception handling features that allow programmers to handle both errors and Java exceptional events on their own.
Hence reading this article, you will learn the following:
- What is Java Exception?
- Types of exceptions in Java
- Common Terminology of Java Exception Handling
- Checked And Unchecked Exceptions in Java
- How to Handle an Exception?
- How to Specify an Exception?
- How to Know Whether to handle or Specify an Exception?
- Throwing exceptions
1.What is Java Exception?
Java exception is an unusual condition that generally occurs in a code sequence while the program is being executed. And, when an exception occurs in your code, it completely disrupts the normal flow of the program and abnormally terminates the process, so it must be handled correctly.
2.Types of Exceptions in Java
Generally, there are two kinds of Java exceptions, namely:
Checked exceptions (compile-time exceptions)
Unchecked exceptions (runtime exceptions)
3. Common Terminology of Java Exception Handling
Call Stack
A call stack is an ordered list of the methods called to get to a specific method.
Exception Class and Hierarchy
The exception class identifies the type of error that occurred. Exception classes are part of the inheritance hierarchy, just like every other Java class. Exceptions must extend java.lang.Exception or one of its subclasses.
The hierarchy is also used to group similar kinds of errors. By extending the Exception class or any of its subclasses, you can create your own exception classes.
Exception Object
An exception object is a member of an exception class. When an exceptional event disrupts the normal flow of an application, it is created and handed over to the Java runtime. This is also called “to throw an exception” because in Java you use the keyword “throw” to hand the exception to the runtime.
Besides, whenever a method throws an exception object, the runtime searches the call stack for code to handle it.
Also Read: What is Java Buffer pool in Memory Space? – A Quick Guide
4. Checked and Unchecked Exceptions in Java
Java supports checked and unchecked exceptions.
Checked exceptions are also called compile-time exceptions, as they occur during compile time. Handling checked exceptions is mandatory. Some of the most common Checked exceptions in Java include:
- IOException
- ParseException
- InterruptedException
- InvocationTargetException
- NoSuchMethodException
Unchecked exceptions are also called runtime exceptions, as these issues occur during runtime and it is not mandated to specify or handle these exceptions. Some of the most common Unchecked exceptions in Java include:
- NullPointerException
- ArrayIndexOutOfBoundsException
- StringIndexOutOfBoundsException
- NumberFormatException
- ArithmeticException
- ClassCastException
- IllegalArgumentException
- IllegalStateException
5. How to Handle an Exception?
Handling Java exceptions happens with the try, catch, and finally blocks. They can be used to define how to handle exceptions when they occur.
Try blocks should include code that might throw an exception. If your code throws more than one exception, you can choose whether to:
Use a separate try block for every statement that may throw an exception or
Use one try block for several statements that could throw multiple exceptions.
Each Catch block should handle exceptions thrown by the try blocks. The finally block gets executed whether or not an exception is thrown after the successful execution of the try block or after one of the catch blocks.
There is no limit to add catch blocks, as you can include as many Catch blocks as you want. However, you can add only one finally block to each try block.
After the try and catch blocks have been executed, programmers usually use finally blocks to do cleanup.
6. How to Specify an Exception?
If you don’t handle an exception within a method, it will propagate in the call stack.
Additionally, if it’s a checked exception, you need to specify that the method might throw it. Add a throws clause to the method declaration to accomplish this. As a result, all calling methods must handle or specify the exception themselves.
Similarly, if you wish to specify that a method might throw an unchecked exception, you may do so.
public void doSomething(String input) throws MyBusinessException {
// do something useful …
// if it fails
throw new MyBusinessException(“A message that describes the error.”);
}
7. How to Know Whether to handle or Specify an Exception?
It usually depends on the use case whether you should handle or specify a java exception. As you might expect, it’s difficult to provide a recommendation that works for all use cases.
For this, you can generally ask yourself the following questions:
Can you handle the exception within your current method?
Are you able to anticipate the needs of all your class members? And would handling the exception satisfy these needs?
If the answer to both questions is “yes”, you should handle the exception within your current method. In all other situations, it’s best to specify it. This allows the caller of your class to implement the handling according to the current use case.
8. Throwing exceptions
In Java, throwing exceptions is a specific programming technique. An exception can only be caught if it was thrown before, either by the Java platform or by custom code. In Java, exceptions are thrown with the throw statement. For example, ArrayIndexOutOfBoundsException, NullPointerException, and IOException were all thrown automatically by the Java platform.
8.1. The Throw Statement
Throwable objects that inherit from the Throwable class can be used with the throw statement. Any block of code explicitly throws an exception. A catch block must follow each throw statement inside a try block.
8.2. The Throws Statement
Java has a throws statement in addition to a throw. Any method that might throw a checked exception can use it in its signature. As an example, let’s say that the method doesn’t want to and cannot handle a checked exception that will prevent the code from compiling. With the throws keyword, you can indicate that the caller needs to handle this exception in its own try-catch block.
Need help Finding Java exceptions?
Finding Java exceptions can be difficult. But with Seagence, one of the popular tools for production monitoring, you can find all defects including unknown defects in your application, and resolve them with greater speed and accuracy in real-time.
It also records and indexes all transactions, exceptions (caught, uncaught, and swallowed) and errors so you won’t miss anything when you want to investigate. You can just go about fixing the code. This way, you can save time and use it for other productive tasks.
Are you ready to make your users happy? Then talk to our support team about your project needs and we will work with you to help create technological solutions.