exception handling in the api - java

I have a java interface that has a method as below -
List<TalkDO> process() throws DurationException;
DurationException is unchecked exception.
I am writing an implementation for this function where I read data from a file and process each line one by one. File read in requires to handle FileNotFoundException and IOException. I have to throw this exception to caller and to let it know that these 2 exception has occered but throwing this exception will make it like
List<TalkDO> process() throws IOException, FileNotFoundException
Which is not allowed in java. What could be my approach, I dont want to catch and handle IOException and FileNotFoundException in my process method

As you have multiple implementations of your interface and according to your comments some don't use File, I think that providing an interface that specifies exceptions of every implementations may be cumbersome for clients.
Why force a client to catch FileNotFoundException if he uses an implementation that cannot throw it?
A more flexible way would be to declare only throwing runtime exceptions in List<TalkDO> process().
In your implementation, you should catch checked exceptions and re-throw
a RuntimeException version of them.
In this way, each client will catch the exception he needs to.
Interface
public MyInterface {
public List<TalkDO> process() throws DurationException, IORuntimeException, FileNotFoundRuntimeException
}
Implementation using File
public MyFileImpl implements MyInterface{
public List<TalkDO> process() throws DurationException, IORuntimeException, FileNotFoundRuntimeException{
...
try{
}
catch (IOException e){
throw new IORuntimeException("your msg", e);
}
catch (FileNotFoundException e){
throw new FileNotFoundRuntimeException("your msg", e);
}
}
Implementation without using File
public MyInMemoryImpl implements MyInterface{
public List<TalkDO> process() throws DurationException {
...
}
}

throws DurationException, IOException, FileNotFoundException is not
allowed in Java
This is not correct, you can specify multiple exceptions in the method signature using the throws clause, you can look here on this.
Also, one important point is that it is not good practice to specify the unchecked exceptions (like your DurationException) in the method signature, it will make the method signature to clutter, look here for more details.
What could be my approach, I don't want to catch and handle IOException
and FileNotFoundException in my process method
You either have to catch or throw the checked exceptions and say if you don't want to propagate these exceptions as checked exceptions to the caller, you can wrap these checked exceptions into unchecked (runtime exceptions).
It is saying process()' in 'FileInputProcessor' clashes with
'process()' in 'InputProcessor'; overridden method does not throw
'java.io.FileNotFoundException
The important point about Java exceptions is that you can't throw new checked exceptions from the overriding methods, so you need to convert them into unchecked/RuntimeException objects. So, the solution is in your implementation class, you need to wrap the checked exception and throw a new RuntimeExcetion (just create your own custom BusinessException i.e., project specific).

Related

Add auto-clear notification on Cordova FirebaseX plugin [duplicate]

New Java programmers frequently encounter errors phrased like this:
"error: unreported exception <XXX>; must be caught or declared to be thrown"
where XXX is the name of some exception class.
Please explain:
What the compilation error message is saying,
the Java concepts behind this error, and
how to fix it.
First things first. This a compilation error not a exception. You should see it at compile time.
If you see it in a runtime exception message, that's probably because you are running some code with compilation errors in it. Go back and fix the compilation errors. Then find and set the setting in your IDE that prevents it generating ".class" files for source code with compilation errors. (Save yourself future pain.)
The short answer to the question is:
The error message is saying that the statement with this error is throwing (or propagating) a checked exception, and the exception (the XXX) is not being dealt with properly.
The solution is to deal with the exception by either:
catching and handling it with a try ... catch statement, or
declaring that the enclosing method or constructor throws it1.
1 - There are some edge-cases where you can't do that. Read the rest of the answer!
Checked versus unchecked exceptions
In Java, exceptions are represented by classes that descend from the java.lang.Throwable class. Exceptions are divided into two categories:
Checked exceptions are Throwable, and Exception and its subclasses, apart from RuntimeException and its subclasses.
Unchecked exceptions are all other exceptions; i.e. Error and its subclasses, and RuntimeException and its subclasses.
(In the above, "subclasses" includes by direct and indirect subclasses.)
The distinction between checked and unchecked exceptions is that checked exceptions must be "dealt with" within the enclosing method or constructor that they occur, but unchecked exceptions need not be dealt with.
(Q: How do you know if an exception is checked or not? A: Find the javadoc for the exception's class, and look at its parent classes.)
How do you deal with a (checked) exception
From the Java language perspective, there are two ways to deal with an exception that will "satisfy" the compiler:
You can catch the exception in a try ... catch statement. For example:
public void doThings() {
try {
// do some things
if (someFlag) {
throw new IOException("cannot read something");
}
// do more things
} catch (IOException ex) {
// deal with it <<<=== HERE
}
}
In the above, we put the statement that throws the (checked) IOException in the body of the try. Then we wrote a catch clause to catch the exception. (We could catch a superclass of IOException ... but in this case that would be Exception and catching Exception is a bad idea.)
You can declare that the enclosing method or constructor throws the exception
public void doThings() throws IOException {
// do some things
if (someFlag) {
throw new IOException("cannot read something");
}
// do more things
}
In the above we have declared that doThings() throws IOException. That means that any code that calls the doThings() method has to deal with the exception. In short, we are passing the problem of dealing with the exception to the caller.
Which of these things is the correct thing to do?
It depends on the context. However, a general principle is that you should deal with exceptions at a level in the code where you are able to deal with them appropriately. And that in turn depends on what the exception handling code is going to do (at HERE). Can it recover? Can it abandon the current request? Should it halt the application?
Solving the problem
To recap. The compilation error means that:
your code has thrown a checked exception, or called some method or constructor that throws the checked exception, and
it has not dealt with the exception by catching it or by declaring it as required by the Java language.
Your solution process should be:
Understand what the exception means, and why it could be thrown.
Based on 1, decide on the correct way to deal with it.
Based on 2, make the relevant changes to your code.
Example: throwing and catching in the same method
Consider the following example from this Q&A
public class Main {
static void t() throws IllegalAccessException {
try {
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
System.out.println(e);
}
}
public static void main(String[] args){
t();
System.out.println("hello");
}
}
If you have been following what we have said so far, you will realise that the t() will give the "unreported exception" compilation error. In this case, the mistake is that t has been declared as throws IllegalAccessException. In fact the exception does not propagate, because it has been caught within the method that threw it.
The fix in this example will be to remove the throws IllegalAccessException.
The mini-lesson here is that throws IllegalAccessException is the method saying that the caller should expect the exception to propagate. It doesn't actually mean that it will propagate. And the flip-side is that if you don't expect the exception to propagate (e.g. because it wasn't thrown, or because it was caught and not rethrown) then the method's signature shouldn't say it is thrown!
Bad practice with exceptions
There are a couple of things that you should avoid doing:
Don't catch Exception (or Throwable) as a short cut for catching a list of exceptions. If you do that, you are liable catch things that you don't expect (like an unchecked NullPointerException) and then attempt to recover when you shouldn't.
Don't declare a method as throws Exception. That forces the called to deal with (potentially) any checked exception ... which is a nightmare.
Don't squash exceptions. For example
try {
...
} catch (NullPointerException ex) {
// It never happens ... ignoring this
}
If you squash exceptions, you are liable to make the runtime errors that triggered them much harder to diagnose. You are destroying the evidence.
Note: just believing that the exception never happens (per the comment) doesn't necessarily make it a fact.
Edge case: static initializers
There some situations where dealing with checked exceptions is a problem. One particular case is checked exceptions in static initializers. For example:
private static final FileInputStream input = new FileInputStream("foo.txt");
The FileInputStream is declared as throws FileNotFoundException ... which is a checked exception. But since the above is a field declaration, the syntax of the Java language, won't let us put the declaration inside a try ... catch. And there is no appropriate (enclosing) method or constructor ... because this code is run when the class is initialized.
One solution is to use a static block; for example:
private static final FileInputStream input;
static {
FileInputStream temp = null;
try {
temp = new FileInputStream("foo.txt");
} catch (FileNotFoundException ex) {
// log the error rather than squashing it
}
input = temp; // Note that we need a single point of assignment to 'input'
}
(There are better ways to handle the above scenario in practical code, but that's not the point of this example.)
Edge case: static blocks
As noted above, you can catch exceptions in static blocks. But what we didn't mention is that you must catch checked exceptions within the block. There is no enclosing context for a static block where checked exceptions could be caught.
Edge case: lambdas
A lambda expression (typically) should not throw an unchecked exception. This is not a restriction on lambdas per se. Rather it is a consequence of the function interface that is used for the argument where you are supplying the argument. Unless the function declares a checked exception, the lambda cannot throw one. For example:
List<Path> paths = ...
try {
paths.forEach(p -> Files.delete(p));
} catch (IOException ex) {
// log it ...
}
Even though we appear to have caught IOException, the compiler will complain that:
there is an uncaught exception in the lambda, AND
the catch is catching an exception that is never thrown!
In fact, the exception needs to be caught in the lambda itself:
List<Path> paths = ...
paths.forEach(p -> {
try {
Files.delete(p);
} catch (IOException ex) {
// log it ...
}
}
);
(The astute reader will notice that the two versions behave differently in the case that a delete throws an exception ...)
More Information
The Oracle Java Tutorial:
The catch or specify requirement
... also covers checked vs unchecked exceptions.
Catching and handling exceptions
Specifying the exceptions thrown by a method

Custom Exception as checked Exception

In Java, if we create custom exception by extending Exception class then it will be considered as checked exception. By definition, checked exception are forced by the compiler like if we are writing below code then we are bound to catch FileNotFoundException
try{
fis = new FileInputStream("abc.txt");
}
catch(FileNotFoundException e)
{
System.out.println("The source file does not exist. " + e);
}
In order to invoke custom exception, I need to explicitly throw it. So how this is checked then? It should be unchecked as compiler is not forcing me anything.
Regards
Shaikh
The checked/unchecked refers to the requirement of handling the exception by the code that uses your method throwing exception.
Say You throw an unchecked exception in your method (RuntimeException or its subclass). You do not have to signal that your method throws it and anyone that uses your code does not need to explicitly handle it.
However if You throw checked exception (Exception that isn't subclass of RuntimeException) then your method must explicitly say that it throws exception and anyone that uses your code must handle that exception - either by also declaring their method as method that throws an exception (rethrow) or by using a try-catch block, around invocation of your method that throws checked exception.

Throw IOException instead of Exception

I have method1() which is called from lots of other methods throughout the code. This is the signature of the method:
public void method1(final Properties properties) throws IOException {}
All methods calling this method also throw IOException.
The actual code in method1() changed, so now instead of IOException it throws some other exceptions that extend Exception and not IOException anymore.
I don’t want to change the signature of all methods calling method1().
Is it ok to create IOException and still throw IOException from method1() and hence the methods calling method1()?
Something like below:
Try {
// code
} catch (Exception e) {
throw new IOException(e.getCause());
}
No, you should not do this, because you will confuse every other developer reading your code or reading stacktraces.
From the software-design point of view, the error happened a lot earlier.
If your code is like an API and used by others, you may better have used Custom-Exceptions and wrapped the IOException as root-cause.
If you have the complete source, you should refactor the source and add another exception signature.
You need to save the original exception as the cause, so you're not losing the original message or stacktrace. Calling e.getCause() in your code example is skipping over the exception that you caught and getting its cause, which is suspicious-looking.
Also it would be better to specify the particular exceptions that the method catches, rather than using a catch-all Exception type. Catching Exception would result in things like NullPointerExceptions getting caught that were not trapped before.
The best thing to do here is change the exceptions thrown by your method to a custom type that doesn't let the implementation details bleed through to the callers. Your method signature should change to
public void method1(final Properties properties) throws SomeCustomException {
try {
.... // do whatever
} catch (AException | BException | CException e) {
throw new SomeCustomException(e);
}
}
This will work technically.
However, catching Exception or Throwable is almost everytime a bad idea (as is throwing them), because you will also catch all other Exceptions, besides RuntimeExceptions.
If you can change the code of all calling classes (i.e. you are not developing a framework/library), you should do so. Because I assume you meant method1() throws a more specific type now.
You may also think about throwing a Subtype of RuntimeException which does not need to be catched, and is a good idea for errors that can't be corrected (e.g. a bad configuration).
(see Clean Code by Robert Martin)

Adding 'throws' on an extended class?

I'm making a simple application with the Socket API, but have run into a small issue that I haven't found the answer for.
The application is supposed to be multi-threaded, so that the main method starts both the server and client threads.
public class UDPClientServer1 extends Thread
However, since the the Socket classes need to throw some specific exceptions, I must also do this:
public void runClient() throws SocketException, UnknownHostException, IOException
and similarly for the runServer() method.
Not that there's anything wrong with that, but is there a more elegant solution? Something along the lines of :
public class UDPClientServer1 extends Thread, throws Exception
Ideally you may want to wrap the exception that your throw, either converting it to a RuntimeException if the error is unrecoverable, or at least a more appropriate / encapsulated exception.
E.g.
public void runClient throws ClientException
{
try
{
// do something
} catch (Exception e)
{
log.error("Exception encountered in client",e);
throw new ClientException("Unrecoverable client exception encountered",e);
// or: throw new RuntimeException("Unrecoverable client exception",e);
}
}
ClientException in the above is your own exception that you would need to create. Its purpose is to encapsulate the implementation details of corresponding exceptions from any calling code.
Using a RuntimeException, however, may be more appropriate if there is no reasonable way for the calling code to respond to the exception. When throwing a RuntimeException you do not have to declare it in the method signature and calling code does not need to explicitly handle it (although it should be handled at some point).

Java custom exception class usage [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Throws or try-catch
I'm writing an API and I wish to write code such that I can raise an exception in a particular scenario. I've created an exception class as follows :-
public class InvalidSeverityException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidSeverityException() {
// TODO Auto-generated constructor stub
}
}
In the codebase im having the following to call the code :-
throw new InvalidSeverityException();
However Eclipse suggests that I either use throws or enclose it within a try ... catch block. I feel that I shouldn't be catching this error and that the developers who use my API should enclose the code within try...catch.
Does that make sense? Am I doing something wrong?
When handling with exceptions in Java you must understand the concept of checked exceptions and unchecked exceptions.
In your case currently you are defining a checked exception, maybe you want an unchecked one.
Here's a brief description about each one of the types:
Checked Exceptions
This exceptions must be part of the method's signature that raises them (or that invokes one method that does) or you must catch them with a try catch block and deal with the problem. Usually checked exceptions are used when there is something that can be done about the error and also when you want the developer to be aware that such error may occur and that has to be handled.
In java java.lang.Exception is a checked exception and all its subclasses will also be checked.
Unchecked Exceptions
This exceptions on the other hand don't need to make part of the method signature, nor you have to wrap methods that throw new in a try catch block. It's just expected that somewhere in the call stack there will be a try catch to handle it, otherwise if it reaches the JVM it will nicely dump you a stacktrace.
In java java.lang.RuntimeException is an unchecked exception and so are all its subclasses.
My opinion
If you are defining an API my suggestion is to use checked exceptions, this is mostly because you explicitly inform the developers using your API that such an exception might occur (so they can handle it anyway they want).
You are correct, you should not catch it. As suggested by eclipse, you should use throws so that the developers will know that your method potentially throws that exception and can then catch it.
.... method() throws YourException{
The method where you have throw new InvalidSeverityException(); should define throws InvalidSeverityException
Example:
void yourMethod() throws InvalidSeverityException
{
........//Some code
throw new InvalidSeverityException();
}
Well then surely you follow the first suggestion by Eclipse and set your method to throw the exception.
public void myMethod() throws InvalidSeverityException {
//throw it somewhere in here so that other
//developer can catch it while calling your method
}

Categories

Resources