How to handle exceptions in Java in functional way?
If I do:
try{
}
catch(Exception e)
{
//log it
// throw exception?
}
and catching the exceptions, what should I return:
Throw the exception?
Else send some error code ( similar to how we handle in C languages )
Because functional programming says:
A function should always return the same type.
Given this scenario, it becomes for certain given input it will throw the exception. Hence its not a pure functional style.
How one should handle this case in Java?
Well even in functional programming, exceptions are not considered as return values.
Take for instance, this segment of SML code:
fun remove_card (cs, c, e) =
case cs of
[] => raise e (* raise exception and stop execution of the function *)
| x::xs => if x = c
then xs
else x::remove_card (xs,c,e)
As you can see, when the exception is raised, we forget about the original return type of the function (a list). It is in this moment that an error situation has happened in your application and you want to handle it to avoid your application from crashing. So, you would not be breaking the purity of your functional programming, since exceptions are thrown, not returned, in order to handle the instability caused by unexpected values/behavior inside your application.
Don't both log and rethrow, if you feel like you want to put some information down and rethrow then wrap the exception. Log only if you are done dealing with this exception and plan on returning a value from the method. Not some error indication like in C, actual value. For example you tried to download something but failed, however you still have a fallback. If you are trying to indicate an error you throw an exception.
Just to add, a lot of times people deal with exceptions by logging in place and returning a null. In the vast majority of cases this is the wrong thing to do as it will only lead to frustration of dealing with NPEs in completely different places
Related
I usually tend NOT TO catch "Exception", but only the exceptions i expect methods to throw, i hear often that is good practice.
But today i came across this issue, an IllegalArgumentException thown by the method URLDecoder.decode(string,encoding).
This method is declared as:
public static String decode(String s, String enc)
throws UnsupportedEncodingException{.....
But it then ('if you look at the source') throws IllegalArgumentException in three different places.
So my question to more experienced programmers is, shall i catch "Exception"? or is this method just been declared wrongly?
Thank you
No you should not catch those exceptions. IllegalArgumentException means a precondition has failed. It's usually caused by a bug in your program, and should crash your application. If the input came from the user, detect the wrong input and show a significant message.
If you have an exception handling policy in your application, then you could let this exception bubble out.
There are two main types of Exceptions in Java, ones that are declared (eg UnsupportedEncodingException) and Runtime exceptions which you do not have to catch (eg IllegalArgumentException). However, if you do not catch the Runtime exception it will crash your thread and potentially your whole application, so it depends on your use case. When I am building big applications with several threads and doing several things at once, when I call 'unpredictable' methods like 'decode' (especially anything that takes in user input, or reads from files that I am not in charge of, etc) I like to catch Exception, so that I can log a nice clean error or return a meaningful error to the user, but the rest of my application carries on running normally. But if I am writing a single-threaded application where you run it, provide some input, and it gives some output, I would not bother catching Runtime exceptions as the output and stacktrace will be printed to the console and I can see exactly what the problem is - and it doesn't matter that the application died because I can fix the problem and run it again.
Just my personal preference - hope that helps!
exists two kinds of exceptions in Java, checked and unchecked exceptions, here are the differences:
Unchecked exceptions: they have RuntimeException in its inheritance tree. The compiler doesn´t requires you to catch'em explicitly.
Checked exceptions: They don´t have RuntimeException in its inheritance tree. You have to catch'em in a try-catch block of declare in a throws clausule.
Basically according to all development methodologies, your code have to be tested, you have to cover all scenarios where unchecked exceptions could occur, because they are generated by errors in your logic code or bad usage of API and you have to correct them. That's why in the final code they should never be catched, because they should never happen.
In the other hand the checked exceptions could happen by causes not related to your code logic i.e. Network loose, Changes in the filesystem priviledges, etc. So you should prepare you code to be ready and catch or delegate the exception.
I hope it helps. And sorry for my english
If you take a look at the source of decode(String s, String enc) you will see three places where an IllegalArgumentException is throw:
"Illegal hex characters in escape (%) pattern - negative value"
"Incomplete trailing escape (%) pattern"
"Illegal hex characters in escape (%) pattern -"
All three errors are not usage errors but real errors in the input. So it is correct that IllegalArgumentException is not a checked exception.
It is correct that UnsupportedEncodingException is a checked exception. The caller could handle it.
To answer your question: Be as specific as possible in what you catch. Don't just catch Exception because you will have no easy way to decide how to proceed. You could could catch both UnsupportedEncodingException and IllegalArgumentException in different catch blocks. You must catch UnsupportedEncodingException.
I want to know the the best programming practice in the following use-case for a method say myMethod--
1) myMethod has some numerical purpose - say modify the contents of an array which is a private variable of the class
2) Before it does so, i need to run some critical checks on the numbers,say check1, check2, check3, any of which if fail, there is no point in going ahead. for eg. check might be to check for any negative numbers in array.
So this brings the question, what should myMethod return, how should the calling function be told that checkX has failed.
You should throw Exceptions if any of these checks fail.
Now the question is what kind of Exception to throw. Checked or unchecked? Checked Exceptions must be caught by the calling code where as unchecked do not (but that means they might bubble up to the top of the call stack all the way up to your main method). There is vigorous debate which is better. Either way, make sure to document which Exceptions are thrown.
In general, you should use checked exceptions for recoverable conditions and unchecked exceptions for programming errors (Effective Java 2nd ed Item 58)
there are many built in unchecked Exceptions in Java that you should use in preference to writing your own including but not limited to.
IllegalArgumentException
IllegalStateException
IndexOutOfBoundsException
NullPointerException
Take a look at the core Java methods to see what they throw.
Exceptions are better than return values because:
You must rely on users to check the return value and do something about it.
You are stuck with a method signature that returns a boolean or return code which might not be what you want.
The Exception can have a very descriptive error message explaining why it was thrown.
You can create a custom checked exception as follows:
class ArrayModificationException extends Exception{
public ArrayModificationException(String message){
super(message);
}
}
now in your "myMethod" add following:
void myMethod() throws ArrayModificationException{
//code to check conditions before modifications
//code to modify an array
if(check fails){
throw new ArrayModificationException("cusom message");
}
}
where custom message would be specific message conveying the exact reason of failure.
Of course the called will decide if to handle it or re-throw it. If this is one of conditions where your code should not try to recover itself you can design this as run-time exception and just throw it without throws clause for your method
There is no "best practice" here. It depends entirely on what your code does, where it's being executed, what the caller of the method expects, what should happen in erroneous cases, etc. Context is key here.
One possibility would be to throw an exception from the failing check, which would then be caught in the calling method.
Another option would to have myMethod return a boolean of true if all of the checks pass and the modification/calculation is done, and false otherwise.
As new_web_programmer said, though, it completely depends on what you are trying to do.
In general after a failed validation I do
throw new IllegalArgumentException("... Clue to the error and its repair...");
IllegalStateException is an alternative here.
This enables the function to continue as desired on success.
If the exception must be catched, not propagated, use your own Exception.
If the check failure is expected to be an exceptional circumstance, then throw an exception. Good examples are if a parameter is null but null is disallowed, or if a array index is out of range.
If your functio is supposed to return a reasonable value based on the inputs, such as returning the Point clisest to 0,0 then you could return a reasonable value based upo the check failures. For example, retur null if the array of Points is empty, or if the array itself is null.
In any case, be sure to clearly document (in the method's javadoc) what inputs result in the failure and what the expected behavior is, so that your callers are not surprised.
This brings up a very old debate whether to use exceptions or error codes.
You can read more about it here:
Exceptions or error codes
try{
check1
}catch(Exception e){
throw new CustomException("failed due to check1");
}
Some thing like this may be a better practice.
This question already has answers here:
Why Re-throw Exceptions?
(13 answers)
Closed 9 years ago.
In some legacy code I see this, that an overbroad exception is being caught, and then thrown again, Is this a good practice? Does throw e; rethrow the same exception, or create a new one ?
catch (Exception e) {
StringBuilder sb = new StringBuilder(
"Oops. Something went wrong with id: ");
sb.append(id);
sb.append(". Exception is: ");
sb.append(e.toString());
System.out.println(sb.toString());
throw e;
}
throw e is rethrowing the same exception. At least it preserves the original stacktrace. It's just writing a message to stdout recording some information about what happened, then letting the original exception proceed on its way.
It's not a great practice, it should be enough to log the exceptions in a central place, recording their stacktraces. If you need to add more information (as in the example, where it logs an id), it's better to nest the original exception in a new exception as the cause, then throw the new exception. I would guess this probably occurs in contexts where there is no centralized logging or where exceptions tend to get eaten somewhere.
This is usually a bad practice. catch(Exception e) (sometimes called Pokemon Exception Handling for when you gotta catch 'em all) catches every single exception. Such exception handling is rarely useful because:
It catches runtime exception too.
You lose information about the type of exception that was thrown.
You cannot react to or handle specific exceptions.
Your method signature now is public void whatever() throws Exception, which is rarely useful. Now everything further up the chain has no idea what kind of exception you have thrown; they will have to do instanceof checks which defeats the purpose of catching specific-exceptions entirely.
As far as your second exception is concerned, throw e; throws the same exception object. If you wanted to wrap the exception, you can create a new one, which means you would do something like throw new MyCustomException(e);. You would also need to change your method signature.
If there is nothing further up the chain, I guess this isn't as bad (still isn't great, though). It looks like a method that is trying to log all exceptions that are thrown. However, again, there are better ways of doing this.
throw e does throw the same exception. There might have been reasons for doing this, but there is also a reason not to. In your example code, a message is sent to System.out, but if a stack trace were printed later on System.err, it won't be syncronized, and in fact the two might end up interwoven in your console.
A better approach would be the following:
catch (Exception e) {
StringBuilder sb = new StringBuilder(
"Oops. Something went wrong with id: ");
sb.append(id);
sb.append(". Exception is: ");
sb.append(e.toString());
throw new Exception(sb.toString(), e); // The original exception is an argument
}
This will create a new Exception with the modified message, and append the original Exception to the stack trace to help with debugging.
My best guess would be it is trying to have two layers of protection. Making sure that an error message is displayed and also asking the client to handle the exception the way it wants to because the catch clause is not doing anything to recover from the exception.
I won't consider it good/bad practice. Depending on your requirements you can consider to go either way like there might be 100 of different clients using your API and each one of them has a different way of recovering from an exception. By displaying what went wrong it is adding a default action layer just below the layer where client decides on how it will handle the exception.
Now back to your question. I think throw e throws the same exception object. As exceptions are objects in java you need to create a new exception object before you can throw it which I can't see happening in your code.
It can be a good practice. I think I always use conversion to RuntimeExceptions during prototyping. After this if there is a need one can change this into better exception handling. For this my purpose there is an utility class in Guava called Throwables which makes exception propagation.
In your case however the exception should be converted into a runtime exception, because declaring a method throwing a general Exception is just the same as a method throwing RuntimeException for the calling party. In the first case it 'catches everything', in the latter it 'catches anything'. I have not yet experienced the difference between two of these in real-world applications. So I prefer RuntimeExceptions as they require less typing.
Catching Exception
Checked exceptions (IO exceptions, security errors, concurrency, etc)
Runtime exceptions (anything, unpredicted garbage, see below)
Everything - these are 99% of all errors (there are Errors left however)
Catching RuntimeException
null pointer exceptions, index out of bounds exceptions, access exceptions, + API which wraps propagates exceptions into RuntimeException - this is ALSO A LOT
My point is after when you're catching an Exception you can't really handle all these cases. So it makes no difference except for the less typing for the calling party if you wrap it into a RuntimeException.
So this is regarding an interview question I was recently asked. The interviewer started on this by asking me how we create our custom Exceptions. On answering that, he asked me how I'd create a RunTimeExceptions. I said we'd create them in the same way as we would create the checked Exceptions. Just our custom exception would extend from the RunTimeException class. Then he asked in what scenarios would you create your own RunTimeException. Now I couldn't think of a good answer to that. In none of my projects, we created custom RunTimeExceptions.
I also think that we should never create RunTimeExceptions. JVM can fail only in a finite number of ways and it handles them well. While writing an application we can't predict what runtime exceptions can occur and hence we shouldn't need to handle them. And if we can predict those conditions, they aren't RunTimeExceptions then. Since we neither need new runtime exceptions, nor need a handling of runtimeexceptions, why would we ever need to create a custom RunTimeException. Everything that we can pre-think of as a possible failure condition should be handled at compile time and it would be a checked exception. Right? Only the things that cannot be handled at compile time and the ones that depend on run time things go into the category of RunTimeExceptions.
Even if we write custom RunTimeExceptions and then a custom method that should throw that RunTimeException - how do we make sure that the method will throw that particular RunTimeException. How do we do that mapping. It doesn't seem possible to me.
Am I missing something/ many things here? Kindly advice.
Thanks,
Chan.
I think the interviewer was trying to see if you understand the purpose of runtime exceptions, which is to signal programmer's errors (as opposed to application exceptions, which signal problems with the execution environment).
You can and you should create subclasses of RuntimeException whenever your method needs to signal a condition that amounts to a programming error, and you need to provide additional information regarding the error the exception describes.
For example, consider a class that lets you store data in a sparse multidimensional array. One of the APIs such class would probably provide is a getter that takes an array of indexes. The number of indexes needs to equal the number of dimensions in the array, and each index must be within its bounds. Supplying an array parameter that has an incorrect number of elements, or has one or more element outside its bounds, is a programming error. You need to signal it with a runtime exception. If you want to signal this error, and provide a full account of what went wrong, your subclass IllegalArgumentException, a subclass of RuntimeException, to build your own exception.
Finally, there is one more situation when you want to subclass RuntimeException: when you should provide a "regular" exception, but you do not want your users to wrap each call of your API in a try/catch block. In situations like these, you can replace a single method
void performOperation() throws CustomApplicationException;
with a pair of methods
boolean canPerformOperation();
void performOperation();
The first method tells the caller that it is safe to call the second method in the current state; it never throws an exception.
The second method fail only in the state when the first method returns false, making a failure a programming error, thus justifying the use of RuntimeException to signal such failures.
Checked Exception vs Unchecked Exception is a long time debate among Java developers. I'm not be here to ignite the fire, but only want to share with you how I use it in our work.
For example, another service call my server for customer information. The input is customerID, and I will return a customer object
// Web Service interface
public CustomerInfo getCustomerInformation(int customerId, int securityToken) {
check(securityToken);
Customer customer = merchantService.getCustomer(customerId);
return customer.getInfo();
}
// MerchantService
public Customer getCustomer(int customerId) {
return customerService.getCustomer(customerId);
}
What will happen if the system can't find a particular customer? Of course it will throw an exception or return null. But returning null is bad, since it will make you check null everytime calling from a service. So I go with throwing exception:
// Customer service
public Customer getCustomer(id) {
Customer customer = getCustomerFromDB();
if (customer == null) throw CustomerNotExistedException();
return customer;
}
Now the question is whether CustomerNotExistedException is a Exception or a RuntimeException. If it's a checked exception, you will need to catch and process it at the function that calls getCustomer. That means you must catch it at MerchantService. However, all you want is to produce a 404 error at WebService level, so that catching it at MerchantService won't do anything more than throwing the exception again. It pollutes the code.
In the general case, I often use RuntimeException to let some exception "bubble up" to the level in which they can be processed.
For your reference, I would recommend the book Clean code from Robert C. Martin. It explains quite well how we should use exception to handle errors in Java.
You would create your own RuntimeException subclass if:
You don't want it to be a checked exception, because you don't expect callers to explicitly catch the exception. (Personally I believe that checked exceptions are rather overused in the standard library.)
You still want to provide more information than just a message (just the type itself is a helpful starting point in a log).
HibernateException is an example of this in the Hibernate ORM.
I think when you are creating Custom Exceptions , please don't subclass RuntimeException , it defeats the whole purpose of creating the custom exception.
Even if we write custom RunTimeExceptions and then a custom method that should throw that RunTimeException - how do we make sure that the method will throw that particular RunTimeException.
The point here is actually the caller of the method needn't surround that in a try-catch block as it is not a checked exception. Unless you have a good reason to throw a custom unchecked exception , say , just to provide additional custom information for logging etc. don't do that. Another bad implementation will be sometimes you would to just want to catch the checked exceptions in your code and throw custom unchecked exceptions to get rid of all the try-catch in the caller code.
I've been reading about unchecked versus checked questions, none of the online resources have been truly clear about the difference and when to use both.
From what I understand, both of them get thrown at runtime, both of them represent program states that are outside the expected bounds of the logic, but checked exceptions must be explicitly caught while unchecked ones do not.
My question is, suppose for argument's sake I have a method that divides two numbers
double divide(double numerator, double denominator)
{ return numerator / denominator; }
and a method that requires divison somewhere
void foo()
{ double a = divide(b, c); }
Who is responsible for checking the case of the denominator being zero, and should an exception be checked or unchecked (ignoring Java's built in divison checks)?
So, would the divide method be declared as is or as
double divide(double numerator, double denominator) throws DivideByZeroException
{
if(denominator == 0) throw DivideByZeroException
else ...
}
void foo()
{
try{
double a = divide(b, c);
}
catch(DivideByZeroException e)
{}
}
or without a checked exception, as is:
double divide(double numerator, double denominator)
{
if(denominator == 0) throw DivideByZeroException
else ...
}
void foo()
{
if(c != 0)
double a = divide(b, c);
}
and allow foo to make the divide by zero check?
This problem originally arose in a mathematical program I wrote in which users entered numbers and logic classes performed calculations. I was never sure whether the GUI should check immediately for improper values, or whether the internal logic should catch them during calculation and throw exceptions.
Interesting topic indeed!
After reading and trying lots of way to deal with errors in general and exceptions specifically I learned to differ between programmer errors and a expected errors.
Programmer errors should never be caught, but rather crash (!) early and hard. A programmer error is due to a logical fault, and the root cause should be fixed.
Expected errors should always be caught. Also when a expected error is caught a message must be displayed for the user. This has an important implication - If a expected error should not display an error, it's better to check whether the method will throw instead of letting it throw.
So applied to your example I would think "How should this look to the user?"
If a error-message should be displayed (in the browser output, console, messagebox) I would throw an exception and catch it as close to the UI as possible and output the error-message.
If no error message should be displayed I would check the input and not throw.
On a sidenote: I never throw DivideByZeroException nor NullPointerException - I let the JVM throw those for me. In this case you could brew your own exception-class or use a suitable built-in checked exception.
My favorite discussion on the difference in philosophy between checked and unchecked exceptions in Java:
http://www.javapractices.com/topic/TopicAction.do?Id=129
Assume that a checked exception is thrown as a result of a mathematical operation. E.g division (as per your post).
This would mean that every integer division should appear in a try block!
Actually division can throw an ArithmeticException which is unchecked exception so there is no need to catch it.
Actually you should not catch it, since it is an exceptional condition that occured and usually can only be solved by code correction.
In your case your code should have done something prior to actually divide by zero.
If you have reached the step where you allow to actually do the division by zero then there is nothing you can do. The program is erroneous and it is best to be fixed than try to somehow disguise it by throwing/catching an exception
Java exceptions are checked only by the compiler, however java designers decided to split them into multiple categories, basically involving the superclass being extended
java.lang.Exception - known as checked exceptions
java.lang.RuntimeException known as UNchecked exceptions - as bonus java.land.RuntimeException extends java.lang.Exception (to ease the handling in catch blocks, and not only)
java.lang.Error - errors, also unchecked and rarely needed to be handled by user-space code, but knowing them and their variance is a major plus. They include (most famous): linkage error, stackoverflow, out of memory, assertion errors
java.lang.Throwable - Checked! and the mother of all exceptions, few need to directly subclass it, but some does for unknown reasons
So it's about need to declare the exceptions and taking care of proper propagation (on compile only level), unchecked ones are auto-propagated and the developer is not expected to provide handling of unless needed.
Checked ones are generally expected to happen and require extra verbosity in the java, already fluffy code.
Worst practices include: catch (Throwable t){}, for many a reason, usually errors shall not be handled unless necessary and most errors usually spell the thread death either ways.
Short answer as some pros and cons have been named: It is a matter of personal or organisational style. None is functionally better than the other. You (or your project) will have to make your own decisions about whether to use checked or unchecked exceptions, or both.
Oracle's Java Tutorial advices you to use checked exceptions for all errors the application can recover from, and unchecked exceptions for the errors the application cannot recover from. But from my experience most applications may recover from most (maybe not during startup) exceptions. The action that failed will be aborted but the application stays alive.
I would rather only use either checked exceptions or unchecked exceptions. Mixing may result in confusion and inconsistent use. Be pragmatic. Do what makes sense in your situation.
Never explicitly throw RuntimeExceptions. If you ever think you need to then just let the runtime do it rather than using throw.