Java check exception checked unchecked

Checked and Unchecked exception

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

When a code throws an exception, the Java runtime system will propagate or forward this exception to the caller. If the caller has a block of code to handle the exception, the handler handles it. If the caller does not have an exception handling mechanism, the exception is forwarded to its caller and so on. The runtime system does this till it finds a block of code to handle the exception. If the exception is not handled, then the JVM will terminate the program. This block of code that handles an exception is called an exception handler.

In this post, we will see about checked and unchecked exceptions in Java.

Exception handler

doWork is a method that can throw and exception. The caller of the code can handle the exception by catching the code. The snippet of code within the catch block is the exception handler.

try < helper.doWork(); >catch (RuntimeException e)

What are checked and unchecked exception

Java Checked and Unchecked Exception

In Java, all exceptions inherit from the Throwable class. There are two subclasses of Throwable viz., Error and Exception. One of the subclasses of Exception is RuntimeException.

Читайте также:  Php получить домен server

Checked exceptions are those exceptions that are of type Exception (class Exception and its subtypes) except RuntimeException (and its subclasses).
Examples: IOException, SQLException etc.

Unchecked exceptions are those that are either Error or RuntimeException. In other words, classes Error or RuntimeException or those that inherit from Error or RuntimeException are unchecked exceptions.
Examples: ClassCastException, NumberFormatException.

Checked exceptions

Checked exceptions are checked at compile time. If a method throws a checked exception, then the throws clause of the method signature must specify the exception. The code will not compile without this.

  1. Handle the exception (with a catch block)
  2. Declare the checked exception in its throws clause (propagating it back to its caller).

Let us say we have a method that can throw a checked exception (FileNotFoundException). The method will look like

Note, as stated earlier, adding the exception to the throws clause is mandatory. Let us look at the caller of this code when it handles the exception and when it just propagates it back.

Handling exception

The caller handling the checked exception will look like

public class Caller < public void someMethod() < Worker worker = new Worker(); File file = new File(".."); try < worker.processFile(file); >catch (FileNotFoundException e) < e.printStackTrace(); //handle the file not found >> >

The code for handling the exception could have logic to recover from the exception. In this case, if the file is not found, it can re-create the file and call processFile again.

Adding to method signature

In this, the caller decides not to handle the exception. Instead, it leaves it to its caller. It can in turn either handle it or re-throw it back and so on. But, some code in the call chain must handle it. Otherwise, the program will terminate with the thrown exception.

To summarize, the compiler forces you to handle the checked exceptions. In our example, when you just type worker.processFile(file), the compiler will complain. It will ask you to either catch the exception or re-throw it back.

Unchecked exceptions

Unchecked exceptions are not checked during compile time. Hence, the method throwing an unchecked exception will not (need not) declare it in its signature.

public class Calculator < /** * Divides two numbers. * @param a the dividend. * @param b the divisor. * @return the result of division */ public int divide(int a, int b) < if (b == 0) < throw new IllegalArgumentException("Divisor cannot be zero"); >return a / b; > >

Running this code will result in

Exception in thread "main" java.lang.IllegalArgumentException: Divisor cannot be zero

The exception thrown was a RuntimeException. The compiler did not force us to handle it or be prepared for it. Unchecked exceptions are generally programming errors.

Note: Unchecked exceptions need not be always created and thrown. It can result from an exception at runtime. In the above calculator code, if we had not checked for the divisor being zero, it would have thrown an java.lang.ArithmeticException at runtime.

public int divide(int a, int b) < return a / b; //Results in a RuntimeException (unchecked) >>

Conclusion

In this post, we saw what checked and unchecked exception are. Checked exceptions are checked at compile time. The compiler will also force the caller of the method to handle it appropriately. Use a checked exception if the caller can recover from it. For instance, if the file is not found, the caller can create one and retry the call. On the other hand, unchecked exceptions are not checked at compile time. They denote programming errors. These in general should not be caught.

References

Share This Post Share this content

Источник

How to Handle Checked & Unchecked Exceptions in Java

How to Handle Checked & Unchecked Exceptions in Java

In broad terms, a checked exception (also called a logical exception) in Java is something that has gone wrong in your code and is potentially recoverable. For example, if there’s a client error when calling another API, we could retry from that exception and see if the API is back up and running the second time. A checked exception is caught at compile time so if something throws a checked exception the compiler will enforce that you handle it.

Types of Exceptions in Java, Checked vs Unchecked

Checked Exception Examples

The code below shows the FileInputStream method from the java.io package with a red line underneath. The red line is because this method throws a checked exception and the compiler is forcing us to handle it. You can do this in one of two ways.

import java.io.File; import java.io.FileInputStream;   public class CheckedException < public void readFile() < String fileName = "file does not exist"; File file = new File(fileName); FileInputStream stream = new FileInputStream(file); > >

Try Catch

You simply wrap the Java code which throws the checked exception within a try catch block. This now allows you to process and deal with the exception. With this approach it’s very easy to swallow the exception and then carry on like nothing happened. Later in the code when what the method was doing is required you may find yourself with our good friend the NullPointerException .

We have now caught the exception and processed the error in a meaningful way by adding our code to the catch block, the code sequence carries on crisis averted.

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException;   public class CheckedException < public void readFile() < String fileName = "file does not exist"; File file = new File(fileName); try < FileInputStream stream = new FileInputStream(file); >catch (FileNotFoundException e) < e.printStackTrace(); >> >

Throws

We use the keyword throws to throw the checked exception up the stack to the calling method to handle. This is what FileInputStream has just done to you. This looks and feels great — no messy exception code we are writing and we no longer need to handle this exception as someone else can deal with it. The calling method then needs to do something with it . maybe throw again.

As with try catch be wary of always throwing as you need to think who SHOULD be handling the error and what piece of code is best placed to handle it correctly.

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException;   public class CheckedException < public void readFile() throws FileNotFoundException < String fileName = "file does not exist"; File file = new File(fileName); FileInputStream stream = new FileInputStream(file); >>

Unchecked Exceptions in Java

An unchecked exception (also known as an runtime exception) in Java is something that has gone wrong with the program and is unrecoverable. Just because this is not a compile time exception, meaning you do not need to handle it, that does not mean you don’t need to be concerned about it.

The most common Java unchecked exception is the good old NullPointerException which is when you are trying to access a variable or object that doesn’t exist.

So to summarize; the difference between a checked and unchecked exception is that a checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception must be handled either by re-throwing or with a try catch block, a runtime isn’t required to be handled. An unchecked exception is a programming error and are fatal, whereas a checked exception is an exception condition within your codes logic and can be recovered or retried from.

Unchecked Exception Examples

BindException

Because we live in a world where systems are built from lots of small micro services doing their own thing all talking to each other, generally over HTTP, this exception is popping up more and more. There isn’t a lot you can do about it other than find a free port. Only one system can use a single port at any one time and it’s on a first come, first serve basis. Most web applications default to port 8080 so the easiest option is to pick another one.

IndexOutOfBoundsException

This is a very common Java unchecked exception when dealing with arrays. This is telling you; you have tried to access an index in an array that does not exist. If an array has 10 items and you ask for item 11 you will get this exception for your efforts.

import java.util.ArrayList; import java.util.List;   public class IndexOutOfBounds < public static void main(String[] args) < Listlst = new ArrayList<>(); lst.add("item-1"); lst.add("item-2"); lst.add("item-3"); var result = lst.get(lst.size()); > >

The above piece of Java code is a common way to get an IndexOutOfBoundsException . The reason this trips people up is because the size of the array is 3 — makes sense; there are 3 items — but arrays are 0-based so the last item in the array is at index 2. To access the last item, it is always the size -1.

var result = lst.get(lst.size()-1);

Checked Exceptions During Runtime

Below is an example that is very commonly used in micro service architecture. If we received a request and we cannot, say, read data from our database needed for this request, the database will throw us a checked exception, maybe an SQLException or something similar. Because this data is important, we cannot fulfil this request without it.

This means there is nothing we can actually do with this exception that can fix the problem, but if we do nothing the code will carry on its execution regardless.

We could throw the exception to the calling code until we get to the top of the chain and return the exception to the user. By doing that we are then littering all the layers above with an exception that they really do not care about, nor should they. What we really want is an unchecked exception to terminate this request gracefully.

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException;   public class CheckedException < public void readFile() < String fileName = "file does not exist"; File file = new File(fileName); try < FileInputStream stream = new FileInputStream(file); >catch (FileNotFoundException e) < throw new ProcessingException("Error opening file"); >> > >

Above we have our same piece of Java code for handling the checked exception thrown from the FileInputStream method but this time we are throwing our own RuntimeException and because this exception isn’t checked at compile time, we don’t need to declare it.

public class ProcessingException extends RuntimeException < public ProcessingException(String message) < super(message); >>

Declaring your own exception type is as simple as extending the runtime exception class because as we have seen from the diagram at the top, RuntimeException is a subtype of Exception.

Difference Between Checked and Unchecked Exceptions in Java

To summarize, the difference between a checked and unchecked exception is:

  • A checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime.
  • A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn’t required to be handled.
  • A runtime exception is a programming error and is fatal whereas a checked exception is an exception condition within your code’s logic and can be recovered or re-tried from.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

5 ways to reduce noise when logging your JavaScript exceptions
Can Constructors Throw Exceptions in Java

«Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»

Источник

Оцените статью