Should I put throws IllegalArgumentException at the function? - java

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.

Related

Why my Ide is not warning me about handle this exception [duplicate]

I've studied that: With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method.
what its mean?
according to that code there is no need to put try catch block in code,
but i've seen compiler forces to put the code in try catch block.
I'm very confused what they are exactly?
Unchecked exceptions are those that extend RuntimeException class. Compiler will never force you to catch such exception or force you to declare it in the method using throws keyword. All other exception types (that do not extend RuntimeException) are checked and therefore must be declared to be thrown and/or catched.
Checked exceptions are used when you want the caller of your method (i.e the user of your API) to explicitly handle the exceptional case in your API. Checked exceptions are declared when you believe the call will be able to do something meaningful with that exceptional case, like retrying the call, rolling changes back or converting it into some user-readable error message.
If you believe that there is nothing useful the call can do about the exception (especially when it represents a bug, or a wrong usage of your API), then the exception should be unchecked. Also, an API with too many checked exceptions can be annoying to program with (e.g. try using java reflection API=)
Checked Exceptions are useful for handling events that occur in the normal operation of a program. An example would be an IOException that is thrown when a file cannot be opened. These exceptions occur even if there is nothing wrong with the program. It is necessary, therefore, to tell the program how to handle the exception.
Unchecked exceptions are useful for identifying defects in the code. For instance, a NullPointerException is thrown when a value is read on a null object. Thus an Unchecked Exception represents a problem that requires a manual fix by the programmer. It is reasonable for the program to crash in order to avoid erroneous behavior, so a try-catch block is not required (but might be desirable in order to provide mitigation, such as displaying an error to the user).
What is your question exactly?
Compilers shouldn't (and won't) enforce you to try/catch unchecked exceptions, that would go against exactly what they are.
The general idea is that checked exceptions are something you may be able to foresee but may be based on input that is out of your control and that you have to deal with.
Unchecked exceptions will usually represent bugs in your program.
There's a number of people that think checked exceptions are a mistake in the Java platform and they only use them very sparingly or not at all. You can read more about this debate by searching google.
It is because,
Unchecked Exceptions are not a result of programmer's fault. Instead they are the serious consequences where we(programmer) aren't expected to do much with it.
In case of Checked Exception, it is an exception generated because of the programmer's fault & often can be resolved by programmer itself.
Check the following links :
Why RunTime Exceptions are unchecked ?
Checked vs Unchecked Exception ?
All Exceptions are part of run time and not compile time. There are two kinds of exceptions checked exceptions and unchecked exceptions. Examples of checked exceptions are IO Exceptions, ClassNotFound Exception and examples of unchecked exceptions are runtime exceptions. In the case of checked exceptions, error or warning message comes at compile time so that the user will take care of it at runtime by using throws keyword, which is used to throw exceptions to the default catch mechanism system. But in case of unchecked exceptions warning is not there at compile time.
**Checked Exceptions
Exceptions which are to be checked or handled or should be taken care during the time of writing the code are called as checked exceptions.
For eg:
1. we have FileNotFoundException -->which will be occured when we are writing some code related to file classes. There will e defenetly posibility of non existence of file. In such case in order to handle them , we are forced to handle those exception for sure.
2. one more example is ParseException ,which will be occured when we are dealing with date functions.
UnChecked Exceptions
These are the exceptions that are optional to be handled during the time of coding. Its up to us whether we handle them or not. In case if we fail to handle them, There is a chance of getting runtime errors during the exceution.
For eg:
We have something called NullPointerException,ArithemeticException,NosSuchElementFoundException and so on. These are like optional things we dont even have to handle them. More over even jvm or compiler will not recommend us to handle them.**
in simple words,
checked exceptions are those which can be and should be handled by your code(therefore compiler forces you to handle them)
unchecked exceptions are those which lie beyond programmer's control(therefore compiler doesn't forces you to handle them)
use the same rule even while creating your custom exceptions.

Java checked exceptions

I'm trying to understand checked exceptions in Java and have the following query.
Is the following correct: If a method has the potential to throw a checked exception, of any type, that exception must either be
declared using the throws keyword, or
caught by the respective method.
If the above is correct, does this mean that I need to understand every single checked exception that is built in to Java so that I know whether my method will have the potential to throw that exception? Or should I just attempt to compile my code and then amend my code based on the compile-time errors?
If the above is correct, does this mean that I need to understand every single checked exception that is built in to Java [...]?
Yes, your statements are correct, but no one expects you to know of all potential checked exceptions when programming. And you don't have to if you have a compiler, or better, an IDE at hand.
Either you go back and forth between compiler output and code as you suggest in your question, or you install an IDE such as Eclipse which gives you direct notifications if you violate the rule:
does this mean that I need to understand every single checked exception that is built in to Java
I assume you are using some IDE (eg. Eclipse) - if not, you should get one ASAP.
Then, the IDE pretty much continuously compiles the code, so when there's a problem, you will get a red underline near it, and a tooltip bubble telling you what's wrong - eg "Missing throws".
Therefore, your second assumption is basically correct, it just happens behind the scenes:
Or should I just attempt to compile my code and then amend my code based on the compile-time errors?
So no, you don't need to learn all the exceptions.
Also, all checked Exceptions extend Exception, so if you have access to the source, you can check what they are based on. Non-checked exceptions extend RuntimeException.
Rule of thumb: If it's something with I/O, it's usually checked. That's the most common type of exception you will encounter.
whenever you use a method (whether your own or In-built) if you closely follow its method signature, if the method throws some exception you need to throw/handle it explicitly in your code
In this way you will not need to memorize all the exceptions and you will know which exceptions to handle where.
To make life easy use some IDE like eclipse
hope this helps!
Good luck!
If the above is correct
It is...
[...] does this mean that I need to understand every single checked exception that is built in to Java so that I know whether my method will have the potential to generate that exception? Or should I just attempt to compile my code and then amend my code based on the compile-time errors?
Use an IDE! You don't need to intimately know ALL of them.
What you do want to check however is the hierarchy (ie, check the javadoc! That should be a Pavlovian reflex); since exceptions are classes, they inherit one another and, for instance, FileSystemException is a portmanteau exception of java.nio.file to signal a filesystem related problem and it inherits IOException. Catch it before IOException if you want to treat it specially.
As a general rule, catch more specific exceptions first.
Also, DO NOT catch Exception. Never. The problem is that RuntimeException, which is the base exception for unchecked exceptions, inherits Exception, meaning that if you catch Exception you catch all unchecked exceptions. You want to rethrow unchecked ones:
try {
something();
} catch (RuntimeException unchecked) {
throw unchecked;
} catch (Exception e) {
// deal with e
}
Yes you need to know every exception..however if u know super class of that exception than you u don't need to know the subclass of it...for e.g..FileReader throws a exception called FileNotFoundException Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.

If catching null pointer exception is not a good practice, is catching exception a good one?

I have heard that catching NullPointerException is a bad practice, and i think it is sensibly so. Letting the NullPointerException to propagate to the top would allow the detection of a something going wrong. But many times I have seen many of my friends catching Exception directly so that they need not bother about all the different kinds of exceptions that might occur in the above code. Is this a good practice? What are the other kinds of exceptions that are best left unhandled? And besides it also makes sense to me to handle NullPointerException over a specific code where we are sure of the source of the exception. So when are exceptions to be handled and when should they not be handled? And what would be the possible list of exception that are best left unhandled?
Pokemon exception-handling is bad. Especially, if it's an empty block and you're simply swallowing them. You have specifically-typed exceptions for the reason that they actually mean specific things in specific contexts (essentially they're telling you what went wrong). So by catching Exception you're saying that you don't care what those exceptions are and that you don't care what happened. This is probably not what you want.
In general, when catching exceptions follow these rules:
Does it make sense to handle the exception at this level? If yes, then handle it. If not, then propagate.
In conjunction with the first rule, "handling" can also mean, catching, wrapping, and re-throwing. This is a way of preventing abstraction-leakage so that callers of your method don't have to know about the underlying implementation.
An empty catch block doesn't mean that you've handled the exception. That's called "swallowing"; at the very least, you want to log the exception. Sometimes an exception happening is actually part of the logical flow of your code, and so you might want to do something special (but this is, pardon the pun, the exception rather than the rule. It is better to check for situations that cause exceptions rather than incorporating them into the logical flow of your code).
You can easily check for a null value in your code, so there is no need to explicitly catch a null-pointer exception. It doesn't make sense to let a NullPointerException happen (and it's bad practice). Even if you have some code that throws a NullPointerException, and it is code that you do not control and cannot fix, you should determine the input parameters that cause the NullPointerException and specifically test for them.
Another exception that you shouldn't catch is the IllegalArgumentException. This exception means that you've passed in an argument that does not make sense. Instead of catching this exception, you should explicitly test your input parameters to ensure that they are sane and that they cannot cause an IllegalArgumentException.
The 'reason' that catching NullPointerException is considered a bad practice is not because you're supposed to let it bubble up when something goes wrong! Saying any exception is 'best left unhandled' based solely on its type seems like a bad idea.
A NPE is considered the result of a programming error. A strictly correct program should never generate one. The reason seeing it caught is bad is it usually means that the code threw one, and the programmer decided to just catch it and cover it up, rather than fix the broken code that caused it in the first place!
If, for example, you were coupled for business reasons to an API that has a bug inside and occassionally throws a null pointer, it would be perfectly legitimate to catch it, do something about it/inform the user with a better message. Letting 'null' hit the UI just because someone said "Catching Null Pointer Exception is bad" would make no sense!
Catching java.lang.Exception can be legitimate in specific cases, but generally "I'm lazy" is not one of them. :) For example if you're implementing an API and want to make absolutely sure no exception ever comes out of it that isn't in the specification, you might catch Exception and wrap it in some application exception you've defined.
You should only catch an Exception if you can add some value by doing so. Otherwise you should let it pass to the caller.
NullPointerException is usually the result of a bug in your code. How can you sensibly fix this in a catch block?
Not being bothered about Exceptions is not good practice.
In general, the only times you should catch an exception is if you can handle it in some meaningful way. If you can't you should simply let it bubble to the top and terminate the process. For instance, could you recover in some meaningful way from a NullPointerException or I/O error? I think not.
My rules for exception handling:
In general, don't catch exceptions, unless you can handle them in some meaningful way.
Catch exceptions at process/machine boundaries, log the caught exception along with any context available to you and re-throw it. If the exception is a custom exception, you may wrap it in an exception of a type known/useful to the invoking process and throw that.
You may also catch exceptions at a low level, where you have the most runtime context available, log the exception and associated context, then rethrow the exception.
When rethrowing, use throw ; rather than throw caughtException ;. Use of the former syntax preserves the original stack trace; use of the latter syntax creates a new stack trace, beginning with throw caughtException ; -- you lose all the context and call stack up to the point at which the exception was caught.
You may, if you so choose, catch exceptions at a high level and gracefully terminate the process, logging the exception information so as to help debug and correct the underlying problem.
Do not use exceptions as a flow control mechanism (if possible). Exceptions are supposed to be, well, exceptional in nature. Rather, premptively, enforce the caller's end of the contract (preconditions) for any methods you are invoking.
See Bertrand Meyers' book , Object Oriented Software Construction, 2nd ed. for more information.
The main rule about catching exception is that you have to know why you are doing this. Exception class is caught in cases when programmer wants to do generic error processing and he does not really care what exactly happened, the main thing is just something went wrong. In that case he may decide to rollback transaction or do some cleanup.
If you are catching specific exception try to apply the same rule. I you know exactly why you are doing that, then it's to do that. But it's very rare case when someone would want to do something really special in case of NPE.
if you have a graceful way to handle your exception it is useful to catch it, if not hope that the caller has a nice way to handle it.

Checked vs Unchecked exception

I've studied that: With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method.
what its mean?
according to that code there is no need to put try catch block in code,
but i've seen compiler forces to put the code in try catch block.
I'm very confused what they are exactly?
Unchecked exceptions are those that extend RuntimeException class. Compiler will never force you to catch such exception or force you to declare it in the method using throws keyword. All other exception types (that do not extend RuntimeException) are checked and therefore must be declared to be thrown and/or catched.
Checked exceptions are used when you want the caller of your method (i.e the user of your API) to explicitly handle the exceptional case in your API. Checked exceptions are declared when you believe the call will be able to do something meaningful with that exceptional case, like retrying the call, rolling changes back or converting it into some user-readable error message.
If you believe that there is nothing useful the call can do about the exception (especially when it represents a bug, or a wrong usage of your API), then the exception should be unchecked. Also, an API with too many checked exceptions can be annoying to program with (e.g. try using java reflection API=)
Checked Exceptions are useful for handling events that occur in the normal operation of a program. An example would be an IOException that is thrown when a file cannot be opened. These exceptions occur even if there is nothing wrong with the program. It is necessary, therefore, to tell the program how to handle the exception.
Unchecked exceptions are useful for identifying defects in the code. For instance, a NullPointerException is thrown when a value is read on a null object. Thus an Unchecked Exception represents a problem that requires a manual fix by the programmer. It is reasonable for the program to crash in order to avoid erroneous behavior, so a try-catch block is not required (but might be desirable in order to provide mitigation, such as displaying an error to the user).
What is your question exactly?
Compilers shouldn't (and won't) enforce you to try/catch unchecked exceptions, that would go against exactly what they are.
The general idea is that checked exceptions are something you may be able to foresee but may be based on input that is out of your control and that you have to deal with.
Unchecked exceptions will usually represent bugs in your program.
There's a number of people that think checked exceptions are a mistake in the Java platform and they only use them very sparingly or not at all. You can read more about this debate by searching google.
It is because,
Unchecked Exceptions are not a result of programmer's fault. Instead they are the serious consequences where we(programmer) aren't expected to do much with it.
In case of Checked Exception, it is an exception generated because of the programmer's fault & often can be resolved by programmer itself.
Check the following links :
Why RunTime Exceptions are unchecked ?
Checked vs Unchecked Exception ?
All Exceptions are part of run time and not compile time. There are two kinds of exceptions checked exceptions and unchecked exceptions. Examples of checked exceptions are IO Exceptions, ClassNotFound Exception and examples of unchecked exceptions are runtime exceptions. In the case of checked exceptions, error or warning message comes at compile time so that the user will take care of it at runtime by using throws keyword, which is used to throw exceptions to the default catch mechanism system. But in case of unchecked exceptions warning is not there at compile time.
**Checked Exceptions
Exceptions which are to be checked or handled or should be taken care during the time of writing the code are called as checked exceptions.
For eg:
1. we have FileNotFoundException -->which will be occured when we are writing some code related to file classes. There will e defenetly posibility of non existence of file. In such case in order to handle them , we are forced to handle those exception for sure.
2. one more example is ParseException ,which will be occured when we are dealing with date functions.
UnChecked Exceptions
These are the exceptions that are optional to be handled during the time of coding. Its up to us whether we handle them or not. In case if we fail to handle them, There is a chance of getting runtime errors during the exceution.
For eg:
We have something called NullPointerException,ArithemeticException,NosSuchElementFoundException and so on. These are like optional things we dont even have to handle them. More over even jvm or compiler will not recommend us to handle them.**
in simple words,
checked exceptions are those which can be and should be handled by your code(therefore compiler forces you to handle them)
unchecked exceptions are those which lie beyond programmer's control(therefore compiler doesn't forces you to handle them)
use the same rule even while creating your custom exceptions.

Is it okay for constructors to throw runtime exceptions?

When checked exceptions are thrown from methods in a constructor that the constructor can't handle is it okay to catch them and throw them back out as a runtime exception if your sure the application can't handle it and will be useless without the object being constructed?
Yes. This is standard practice.
In Effective Java, 2nd Ed. this is covered by Item 61, "Throw exceptions appropriate to the abstraction". Whether the resulting exception is checked or unchecked is a also covered by Effective Java in Item 58, "Use checked exceptions for recoverable conditions and runtime exceptions for programming errors".
That this is a constructor rather than a normal method isn't really an issue. (In fact, constructors arguably have more freedom as they are not bound by the super's interface.)
When throwing an exception as a result of another exception it's a good idea to ensure that you're setting the cause on the new exception.
Yes, this is inevitable in many constructors anyway when they call other methods since there is always a possibility that they will already throw unchecked exceptions.
Yes it is completly valid to throw the exception in your constructor. You have little or no other choice but to do this, especially when you are simply trying to construct an object and things just don't work out right.
It's perfectly OK to throw a checked exception to indicate that construction of the object failed, as Chris Jester-Young commented already. Whether it is a good idea to throw an unchecked exception is another issue. You would loose the nagging of the compiler that urges you to catch and handle the exception, which you will certainly want to do.
Yes. Unless you know how the exception should be handled, you're better off throwing it, rather than simply swallowing it and printing out a stack trace (or worse, doing absolutely nothing).
This will help prevent some extremely difficult-to-debug errors later on.
Personally I hate to see constructors throw checked exceptions (as doppeldish already pointed out). Nevertheless, how can you be sure that the application can not handle the exception? Even if the application can't handle it, maybe the user can, by simply trying again?

Categories