When you write a method that throws a checked exception, you must __________.
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. Show
Checked Exception ExamplesThe code below shows the
Try CatchYou simply wrap the Java code which throws the checked exception within a 0.We have now caught the exception and processed the error in a meaningful way by adding our code to the 1 block, the code sequence carries on crisis averted.
ThrowsWe use the keyword 2 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
Unchecked Exceptions in JavaAn 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 5 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
Unchecked Exception ExamplesBindExceptionBecause 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. IndexOutOfBoundsExceptionThis 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.
The above piece of Java code is a common way to get an 7. 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.
Checked Exceptions During RuntimeBelow 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 8 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.
Above we have our same piece of Java code for handling the checked exception thrown from the 0 and because this exception isn’t checked at compile time, we don’t need to declare it.
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, 0 is a subtype of Exception.
Difference Between Checked and Unchecked Exceptions in JavaTo summarize, the difference between a checked and unchecked exception is:
Track, Analyze and Manage Errors With RollbarManaging 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! When should a checked exception be created?Checked exceptions are exceptions that need to be treated explicitly. The code above is a classic way of handling Java checked exceptions. While the code throws FileNotFoundException, it's not clear what the exact cause is — whether the file doesn't exist or the file name is invalid.
How to create a checked exception in Java?Custom Checked and Custom Unchecked
If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class.
How to convert checked exception to unchecked exception?You can write a helper function to convert thrown exceptions to unchecked ones. Essentially you would call something like callUnchecked(() -> getConfigFactory()) in your code and define callUnchecked similar to try { return supplier. get(); } catch (Throwable ex) { throw new RuntimeException(ex); } .
What is a checked exception in Java?A checked exception in Java represents a predictable, erroneous situation that can occur even if a software library is used as intended. For example, if a developer tries to access a file, the Java IO library forces them to deal with the checked FileNotFoundException.
|