How to use throws? - java

I am learning Java and come across the throws keyword. I came to know that it is used for exceptions we cant handle or don't wont to handle.
Why can't we just use exception.printstacktrace? Or is there any situation where throws can perform auto exception handling or it is just a mere keyword for the reader to know that the method can throw that exception?

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords.
And'throws' does not perform any exception handling it just tells to delegate exception handling to caller method as its not done in called method.
exception.printStackTrace()
or
exception.getMessage()
You can print stack trace only when exception catched. Basically java follows a rule Throw or handle with checked exceptions. Handling exception is catching them.
Also remember that some where you always have to handle your exception but you have freedom to choose where in your application flow you want to handle.
And'throws' does not perform any exception handling it just tells to delegate exception handling to caller method as its not done in called method. So that called method is aware of exception it has to handle or throw back again(but as said earlier some where it has to be handled)
PS: there is very nice question for is printstacktrace considered bad

practical usage
If you are working on enterprise applications, and any exception came in middle layers those exceptions need to propagated to controllers this is one of the practical example of throws keyword.
In such applications we write navigation logic in controller and also handle logging, so it's necessary to propagate your exception message to controller layers.

When you declare that your method throws SomeCheckedException, you require of the users of your method to handle that exception (or declare that they throw it themselves if they can't handle it). It's part of the contract of the method.

dont wanna handle? never happen, you always have to handle your exceptions. But when you throw an exception, it means that you dont wanna handle this exception in this function, and you want to deal with this in another place.

Practical Usage depends on person's requirement !
Suppose I developed an API having a method animateImages(InputStream image) Now this method will work fine if a valid image is passed but what if you pass a PDF to this method , this method fails miserably .
So if i will handle the exception , I just put a stackTrace() and log what is wrong but that is of no use for you .
I want you to know the reason and to react accordingly and send the valid Image file or whatsoever you want to do .
This is why we generally throw any Exception when we want the consumer to handle it .

Related

Is catch(Exception) viable for convenience methods if there is an overload that allows proper handling?

I am developing a library for working with files and want to make it as easy to use (i.e. not having to worry about exceptions), but also as complete as possible (i.e. allow for proper exception handling).
To achieve this, I expose two methods. One that allows for normal catching of exceptions:
public void saveChecked() throws IOException, IllegalArgumentException {
// Possibly throw an IOException or IllegalArgumentException
}
...and one that handles all exceptions using a generic Consumer<Exception>:
public void save(Consumer<Exception> handler) {
try {
saveChecked();
} catch (Exception exception) {
handler.accept(exception);
}
}
The intention behind this is, that, if you don't need to differentiate between exceptions and just want to do one simple thing when an exception is thrown (e.g. print the stack trace, show a popup), you can just use the second version instead of having to write out a try-catch block (and making one-liners impossible).
Is this still bad practice even though the API does expose a method which allows proper exception handling for those that need it?
I am developing a library for working with files and want to make it as easy to use (i.e. not having to worry about exceptions), but also as complete as possible (i.e. allow for proper exception handling).
It's java. Exceptions are part of the language. Reinventing the exception system is mostly just going to lead to a bizarre library that doesn't fit in with the rest of java.
do one simple thing when an exception is thrown (e.g. print the stack trace, show a popup)
psv main is allowed to be declared as throws Exception. More generally, if you want to handle all exceptions in the same way, let the exception bubble all the way to the top, and register an exception handler e.g. via Thread.setDefaultUncaughtExceptionHandler.
If you just hate checked exceptions, you probably shouldn't be using java. However, if you somehow must go against the grain, there's always UncheckedIOException that you can throw, which makes that whole 'bubble up to the top, register an uncaught exception handler' a little bit easier.
Is this still bad practice
Yes. Writing non-idiomatic java is bad practice.

What exception should I throw

I am a newbie and learning Java exceptions,
public void function (argument) {
if (condition) {
throw new Exception;
}
}
My confusion is:
If I know like the condition will cause NullPointerException, so I can throw a NullPointerException.
What if the code throw some Exceptions I didn't expect, or say I don't know what is the Exceptions of my code, what should I throw?
Like this link
When to throw an exception?
said: "Every function asks a question. If the input it is given makes that question a fallacy, then throw an exception."
but if the input does make a question a fallacy, but myself don't know this input will cause this fallacy, what should I throw?
Or I should run enough test to find all exceptions and throw them?
I know my question is weird, but if you know what am I saying, please give me some instructions. Thanks
Source: Oracle - The Java Tutorials - "What Is an Exception?":
"After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred.".
Each function that doesn't directly provide a means to handle an exception returns to a caller with either a successful result or an unhandled exception for the caller to handle.
A function that might encounter an exception and is able to handle it avoids the need to have the caller handle it, similarly a caller that can handle exceptions from its subroutines saves writing the handler in the subroutines.
If the caller is calling various subroutines that might all encounter the same error conditions then handling it in the caller results in less code (and consistency in the handling of the exception) over rewriting similar code in each subroutine which would be better handled by the caller.
Source: Oracle - The Java Tutorials - "Unchecked Exceptions — The Controversy":
"If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.".
Try to predict what could happen and handle it if possible, always trying to let the caller do the work if it's duplicated in multiple callees and having the 'leaves of the tree catch the light work'.
Or I should run enough test to find all exceptions and throw them?
Writing a test harness can be separated or part of the code, if it's internal then usually (but not always) you'd want to define it out of the release version.
I think an exception should be thrown:
if a function cannot satisfy an established condition
it cannot satisfy the precondition of a function it is about to call
if this can cause instability for other members
There are some other situations that can be taken into consideration, but basically for me these are the main things to keep in mind.

Transforming Exceptions thrown from an external library in a centralized way

I would like to ask a code style question around Java Exceptions. I am using Java to call a C/C++ library using JNI. The convention in the library I am using is that most of the methods I can call will throw the same exception type for all errors. Let's call that a LibException. Now LibException is really a wrapper exception for a multitude of errors that can come up ranging from authentication problems, connection problems or more serious problems like corrupt input etc. LibException also contains an error code int as well as the error description string.
Even more confusingly LibException can also wrap one of my own exceptions if I throw it at the library in a callback! What I mean by that is that I sometimes provide a callback method, it is called by the library and I sometimes have to throw an exception in the callback. In that case the library picks up the exception, wraps it up in a LibException and throws it back at me in the original method call.
I would like each of the underlying problem to be handled differently. Authentication problems need to be shown to the user so he can retry, users should be notified of connection problems, but more serious problems may have to trigger my diagnostics report system (an automated mechanism that can send me parts of the logfile for debugging) and of course any exceptions I throw towards the library in the callback need to be rethrown as the original exception type.
Since I am calling different methods at multiple locations, I thought it would be a good idea to put some structure around the exception handling of LibExceptions. This is to avoid code repetition but most importantly to make sure that the different exception types are handled properly and that future me does not forget to, for example, notify the user that authentication failed.
I have tried a bunch of approaches but I am not entirely happy with the code structure I get so I would like some ideas on best practices from the community.
Static method that includes logic to sort the exceptions and throw a bunch of other exceptions
public static void handleException(LibException e) throws AuthenticationException, ConnectionException, SeriousException, MyException (MyException would be my exception that I throw in the callback)
+ve This works well in that it forces the handling of all the thrown exceptions.
+ve If a new exception type is added, the compiler would force me to handle the new exception
-ve Even though handleException() is a method that always throws an exception, the compiler (rightly) does not know this. This means that if we use handleException() in a method that has to return something, the compiler complains that a return type was missed. To make the compiler happy I have to throw another exception right after calling handleException() so the compiler understands that it will not be getting a return value because an exception is definitely thrown.
-ve I don't like the line that looks like Handler.handleException(libEx) since it's not entirely obvious that it throws a bunch of exceptions.
-ve Hard to customize the exception messages with context from the location the exception occurred (i.e. which URL we could not connect to).
A method that returns an enum with the different types of exceptions that I defined. Based on the enum I can then create the different exceptions to throw.
public static ExceptionTypeEnum Handler.
+ve Since I create the exceptions, I can now customize some error messages with extra context
-ve I could still forget to handle an enum (especially if I create a new category in the future)
-ve I still need a bunch of custom code to create the exceptions at every place I catch a LibException
Similar to #2 but instead of an enum return I could have multiple methods such as isAuthenticationException(libEx) or isConnectionProblem(libEx) and then accordingly throw the exceptions myself.
-ve I would definitely forget to handle all sections properly especially if a new exception type is added later.
The exception handler could return an exception to throw up. But since we throw a number of different exceptions the getException() method would have to return the Exception base class. This means that exception handlers would have to have prior knowledge of what exceptions could be thrown and also catch the Exception class making my exception handling more difficult.
Now in case I confused everyone with this question, I guess what I am trying to find an elegant solution to is similar to the problem described on section 'Checked exceptions inappropriately expose the implementation details' on page http://www.ibm.com/developerworks/java/library/j-jtp05254/index.html
Does the community have any other suggestions of a coding method to properly and elegantly handle these LibExceptions?

Why should we write custom exception classes in Java

What is the purpose of writing custom exception classes when mostly what it does is same.
For eg, NullPointerException:
class NullPointerException extends RuntimeException {
private static final long serialVersionUID = 5162710183389028792L;
public NullPointerException() {
super();
}
public NullPointerException(String s) {
super(s);
}
}
This is the basic template for most exception classes that I have seen and created.
One purpose I can think of is in handling these exception.But then cant this be based on Exception Message?. Mostly we write single handling code for each exception type. I know there are 'exceptions' to this.
But is there anything more to it? Isnt this repeating yourself where only the class name changes?
Also are there any JDK Exception classes that has some code than this?
I can think of several reasons:
Having multiple exception classes allows the programmer to be specific in their catch clauses, and only catch the exceptions they care about and know what to do with.
An exception class can carry information about the error that's caused the exception. For example, ArrayIndexOutOfBoundsException carries the offending array index, and SQL exceptions tends to carry database-specific error codes and messages.
Exception specifications -- that list exception classes -- can be used to check correctness at compile time.
Well, simply put, if you do not need special exception class, you should not make one. If you do, then you make one. There's no magic to it really.
If you're making a library, then you should of course think from the point of view of the developers using the library (even if it is just you): does your library throw exceptions for specific reasons and could the library user possibly want to catch specifically these, because they can realistically do something about it (just logging isn't reason enough, IMO).
Example with standard exception classes: Caller of a method might want to convert IndexOutOfBoundsException to null return value, while letting other exceptions to propagate normally.
If you want your custom exception to be handled in default ways, you extend right existing exception class, such as IOException. You can then catch your specific IO exception when you want to do something specific just there, but also let it be handled like any other IOException when you don't need special handling (can't do anything useful to recover).
If you have a totally custom exception which should never be caught by a superclass catch, which always should have specific catch block, then you extend Exception directly.
I think it's pretty rare to need to extend RuntimeException, because if it an exception meant to be caught it should be Exception subclass, and if it's meant to end the program or just generate log output, then it should be covered by default RuntimeException implementations with custom message string.
You need to have your client code know what exact exception happens by which part of code. so you need to let exception semantic and distinguished from other code block.
How to do this:
Define new exception class, so the class name tells what happens
Define a unifed/generic exception class which wraps code, message or other info. the code can tells what happens.
To summarize it, Do something let your exception have some meaning/semantics, and let its client know what exactly happens.
We will have a freedom to add few more methods into our Exception class which helps the client like rootCauseOfException(),description(),solution(),suggestions() etc.
Can refer below link:
https://stackoverflow.com/a/22698673
If your project has interdependent modules then you can maintain exception hierarchy also in the same dependency hierarchy so that if you catch single Exception in base layer then all the interdependent modules exceptions will be caught.
You can also mask some sensitive data like ip ,port etc before sending to client side. If custom exceptions are not used then some sensitive data can may get leaked to slient.
You can provide your own exception message which can be easily understandable by client rather than java's exception message sometimes which may be hard to understand .
It is basically to Handle different Exception in different ways. Say, you might want to do some different operation on ArrayIndexOutOfBoundsException than a NumberFormatException.
or more clearly
}catch (ArrayIndexOutOfBoundsException ex){
//operation 1
}catch (NumberFormatException ex){
//operation 2
}
The main purpose would be identify the custom / app-specific errors. You can also provide some additional methods there. For eg, we have custom exceptions that return custom messages, and also extracts cause and location from the stack trace.

Should I put throws IllegalArgumentException at the function?

I'm building a scientific software with lots of calculations and of course arguments can have wrong lengths etc... So I used IllegalArgumentException class as it seemed right name for the issue, but should I put the throws IllegalArgumentException at the function definition ?
I am asking this because after I wrote it, the Eclipse Editor didn't ask me to surround the function with try and catch. I thought this is how try and catch were enforced. I've read the Exception handling tutorial at Java.com yet I'm not sure I understood the part regarding my question right though.
RuntimeExceptions like IllegalArgumentException are used to indicate programming errors. The program itself should rarely be able to handle it. Someone needs to manually fix the code.
Potential RuntimeExceptions should be documented somehow in the function contract (i.e. javadoc), either with the explicit #throws, or while describing the inputs. If you don't have a javadoc for the function, you may want to add the throws clause just to document the potential pitfalls of using the function, but in general adding throws clauses for runtime exceptions is discouraged.
If giving a wrong length is not actually a programming error, but is an exception situation, I would create a new checked exception (such as BadLengthError). If it is not an exceptional situation, don't use exceptions for flow control.
There's two types of exceptions:
runtime exceptions (like IllegalArgumentException and NullPointerException for example) don't need to be explicitly caught, because they 'shouldn't happen'. When they do, of course, you need to handle them somewhere.
regular exceptions NEED to be caught or declared to be thrown because they represent a more intrinsically difficult kind of error.
You need to read up on Unchecked Exceptions - exceptions which inherit from RuntimeException. They don't need to be declared in the method header.
http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
The last paragraph sums it up:
If a client can reasonably be expected
to recover from an exception, make it
a checked exception. If a client
cannot do anything to recover from the
exception, make it an unchecked
exception.
IllegalArgumentException (along with some others, for example NullPointerException) are examples of a RuntimeException. This type of exception is not what's known as a checked exception. Java requires that methods declare which checked exceptions they throw and that if a called method might throw a checked exception, the calling method should either declare that it throws the exception itself, or catch and handle it.
As such, my concrete recommendation would be no, don't declare it. Certainly, though, you don't want to be catching it. In most cases, you also don't want to be throwing it unless this is unexpected behaviour. If it's quite normal and reasonable for the the method to be getting a value it doesn't like, an Exception is the wrong way to handle it.
You might also want to consider making use of assertions.
the first point when understanding exceptions is that they are for exceptional situations. While thinking about your method you must ask: "Should this method throws an exception if an exceptional value is passed through?" If the answer is "yes", put it in your method declaration.
I don't know if you get the idea, but it's kind of simple. It's just a matter of practice.

Categories