Adding Unused Exceptions to 'throws' - java

Why does the Java compiler allow exceptions to be added via throws even when they're not possibly able to be thrown?
example:
private static void foo() throws java.io.FileNotFoundException {
System.out.println("no possible FileNotFoundException here");
}
The above code compiles just fine, but it's not possible for a FileNotFoundException to be thrown.

I would suggest maintenance: because you might want to change that method later to add an operation that could throw a FileNotFoundException, and you want to force all callers of this method to know what to do if that method should be changed to throw FileNotFoundException in the future.
Another manifestation of the issue is that a subclass may override this method and throw the exception, and this cannot be determined by compiling the superclass alone.

Because the compiler isn't smart enough to find out every exception?
It sounds quite logical that Java can't know the possible outcomes for all algorithms. Just like a programming language can never prove a mathematical exception, it can only execute mathematics.
This means that an obvious mathematical "infinite loop", isn't always obvious to the programming language. I think that for such reasoning, the compiler doesn't bother looking at what will be executed.
If the compiler would have to pre-check for all exceptions the coder writes, it might spend "days" checking the code. All in all it just seems better to have the programmer responsible for the exceptions. Either way, it doesn't hurt.

Checked exceptions are validated by the compiler only in the try { } block, method bodies are not validated. There are multiple reasons, the complexity of such check being one, the fact that a child class can override the method and decide to throw the exception is a second.

In Netbeans 7.3.1, this would show up as an "unreported exception" and it will warn you that it must be caught or declared. So it would be an error. It depends on your tool.

Related

Declaring runtime exceptions

What is the guideline for methods declaring runtime exceptions?
Let's say I call a 3rd party routine that throws SQLException. Is it permissible/standard/acceptable for that routine to be able to throw RuntimeExceptions without declaring that it does so?
As always, I am surprised by the confusion my questions cause :-D This is probably because I am confused.
In the following, the callable is a lambda that issues a commit, and this throws SQLException. callable.call throws Exception.
private doThis(Callable<T> callable) throws SQLException {
try {
return callable.call();
} catch (SQLException e) {
// do stuff
throw e;
} catch (Exception e) {
break; // Eats any exception from call() which makes me scream internally.
}
}
What I surmise from this is that the coder wanted doThis to throw a SQLException. However, the nature of using the Callable meant that the routine had to throw an Exception unless the coder did something. So he caught Exception and swallowed it. But Exception is the parent is RuntimeException, so we're eating those too.
What am I to do? Making doThis throw Exception seems clumsy and random. Wrapping any exception being thrown in a RuntimeException and raising that preserves the coder's intent but seems suspect.
EDIT -
ok, I have learned, thank you. Now the question is, what to do about it. Clearly, eating the exception is a bad idea. Diluting the SQLException as declared seems not great.
How does the collective wisdom of SO feel about wrapping the Exception in a RuntimeException?
...
} catch (Exception e) {
throw new RuntimeException(e);
}
What am I to do? Making doThis throw Exception seems clumsy and random. Wrapping any exception being thrown in a RuntimeException and raising that preserves the coder's intent but seems suspect.
This method's sole reason for existence appears to be to perform special handling (// do stuff) in case of a SQLException. To handle that error correctly, some assumptions about what the Callable is doing must hold. For the sake of argument, perhaps the "stuff" is marking a particular database connection for rollback, assuming that the Callable used it do some work that may have partially failed.
Yet, this method accepts Callable. That doesn't impose any limitation on what the called function might do, why it might throw a SQLException, or what a SQLException might mean if it does arise. This code feels wrong, because it is wrong to make these very specific assumptions about an open-ended, black-box function like Callable. And, it's probably unnecessary. This is a private method, so you know everything about the methods that call it, and you can modify them to make it clear how things work together.
Instead, define your own (functional) interface. Declare the specific exceptions your helper method can handle, and document any other requirements for implementations. If, in fact, the "stuff" done in your helper method involves a database connection that is a member of the object, you might define the interface like a Consumer or Function, but with SQLException or other errors.
Here's a hypothetical example:
private final Connection db;
#FunctionalInterface
private interface DatabaseOperation<T> {
T apply(Connection db) throws SQLException;
}
private <T> T withRollback(DatabaseOperation<T> op) throws SQLException {
try {
return op.apply(db);
} catch (SQLException ex) {
db.rollback();
throw ex;
}
}
None of this is to say that Callable or other core functional interfaces are bad. You shouldn't create new, non-standard functional interfaces when the pre-defined interfaces would meet your needs. It's just that they don't in this case.
Not sure what you mean.
Is it okay to stick exception types that extend RuntimeException in the throws clause of a method?
Java implies certain things and usually you can't undo these things.
For example, all java files act like they have import java.lang.*; at the top even if don't write that. All classes that don't have an extends clause act like they have extends java.lang.Object...
and all methods act like you have throws RuntimeException, Error on them whether you write it or not.
It's legal to write import java.lang.*;, although it would be completely pointless to do this. It is similarly legal to write:
void foo() throws RuntimeException {}
even though this is rather pointless. However, unlike import java.lang.*;, adding some specific runtime exception can be useful in the sense that it documents (It has absolutely no effect whatsoever on what the code does). Some linting tools (I would disagree with the style they are espousing, though!) flag it down as 'useless code' but I wouldn't be so hasty. For example, this method:
public static int parseInt(String in) throws NumberFormatException {
..
}
is declaring the NFEx for no programmatic purpose (NFEx is a RuntimeException and all methods trivially can throw those without declaring them), but it is documentary: It highlights that that's an exception you should be taking into consideration when invoking this method / it's the obvious "thing you are looking for" (in the sense that 'soooo... what if I pass a string that does not contain a number to this method, what happens then' - is the obvious question to ask).
So, do it, if that's your intent. Your javadoc should probably have a:
* #throws NumberFormatException If the provided {#code input} is not parseable as an integer number.
or similar, for each explicit RuntimeException you care to state.
Is it okay to wrap SQLException to RuntimeException
Usually: No. The notion of declared checked exceptions is that they are part of your signature. A signature is all about what a method does. It is very much not at all about how it does so.
Thus, the crucial question to ask is: Is the SQLException aspect of it fundamental to what your method does, or fundamental to how it does it?
A trivial example:
saveGame() may simply 'save your game to some persistent storage mechanism'. That's what it does. Perhaps the how involves a database today. Perhaps tomorrow it'll involve the file system. Perhaps next year it's a cloud save system and it involves network access. If the point of this method is merely to force a save, and the method's signature intentionally does not explain how (because you want the future flexibility of changing this, and thus any callers should not assume it's disk, or DB, or network, or anything else), then and only then: SQLException would purely be about the how - and thus it has no place being thrown from the saveGame method. You should wrap it. I highly doubt it's a good idea to wrap that in RuntimeException, I'd invent your own exception (SaveGameException perhaps). Should that exception be checked or unchecked? That depends on too many factors to get into for this answer.
However, something like Files.newOutputStream is different. The what of this method includes the notion that its file based. Fundamentally: It would be nuts if that method doesn't interact with a file system at all and instead opens a database connection. The very name of that method spells it out: It is, after all, in a class named Files - the fact that it interacts with files is a fundamental, unremovable aspect of it. Hence, that method should most absolutely be declared to throws IOException. Similarly, if you have a method called saveToDb, that method should definitely be declared as throws SQLException - and thus, you should not be wrapping your SQLException in anything else.
In rare cases, convenience and intended usage strongly dictates you do not want the exception to be checked. In that case, make an unchecked variant and wrap that. Java itself has UncheckedIOException already - reuse that if it's about IOExceptions. Write the same principle if its about SQLException. However, usually if this comes up you've badly designed your classes - if there's an aspect of your system that is fundamentally tied closely to the notion of interacting with DBs, that entire chain of methods should all be declared to throws SQLException, at which point the need to make that unchecked no longer exists.
Can RuntimeExceptions happen?
Yes, by their nature, RuntimeExceptions can happen at any time. Looking at the greater java ecosystem, RuntimeExceptions cover 3 mostly separate use cases (this isn't getting into what the feature was ever intended for, this is solely about what common java libraries and code actually use them for):
Programming errors (bugs)
The quintessential example is NullPointerException. There is a bug, the bug should cause some kind of RuntimeException to be thrown. We do not want to make such exceptions checked (because nobody likes a catch block that literally is impossible to trigger unless you actively write bugs to do so - what could you possibly stick in the catch block?), but we DO want to throw something: Breaking off the method and 'unrolling' the entire call stack until some general handler deals with the problem (and gets lots of details about where that problem occurred and why) is precisely what we want. Hence, exception good, checked bad - these should be runtime exceptions and generally are.
Similar examples: Many methods that have rules about what you can pass to them which cannot be expressed in the type system (say, a method that requires you pass a non-negative integer) will throw IllegalArgumentException if you pass a negative number to them, for example. Some methods cannot be called when the object is in a certain state, and will throw IllegalStateException or UnsupportedOperationException, both unchecked (subtypes of RuntimeException) - for example, if you attempt to invoke .add() on an immutable list, you'd get that.
Couldn't be bothered
Sometimes checked exceptions can occur but you just don't care, either because you're a lazy programmer who wants to just go home (that'd be quite bad, of course), or because you cannot fathom why a checked exception could occur. For example, an IOException when writing to an OutputStream that is memory based.
IDEs tend to suggest this incredibly stupid 'fix':
try {
code();
} catch (IOException e) {
e.printStackTrace();
}
I do not know why. Mass delusion? At any rate, all IDEs are very wrong, that is bad code, the correct 'I do not want to think about this checked exception right now' handle block is throw new RuntimeException("uncaught", e); - and smart folks have updated their IDEs to auto-generate this. It's wrapping a checked exception in an unchecked one simply for convenience, or because the coder did not think it could happen.
For API/programming model reasons
See UncheckedIOException - usually because the code is designed to be used in stream pipelines which doesn't allow checked exceptions. Somewhat rare.
Unexpected situations
It could be reasonable for the programmer of this library to fail to account for some exotic situation which nevertheless is also reasonable for your specific usage of some library to run into. For example, a third party library could be saving data to whatever OutputStream you provide for it, and that OutputStream might throw a documented unchecked exception for some reason - in which case your library is likely to also throw it. This is rare - you'd presumably know about it, and it comes up only if some library is 'intermediary' - you pass it some object that it, in turn, acts upon, and in that interaction, the runtime exceptions end up getting passed through. Or, the object you pass in doesn't adhere to certain rules. For example, if I hand a comparator that doesn't adhere to the spec (for example, is inconsistent: both a.compareTo(b) and b.compareTo(a) return a negative number - the Comparator spec says you should not do that) to some library, and that library ends up throwing some undocumented unchecked exception for this, I wouldn't blame the library author.
The 'first' case (code bugs) should be documented. For example, Integer.parseInt indeed documents that a NumberFormatException is thrown if you pass a string that doesn't contain something parseable to an int. List's add documents that it might not be supported in which case UnsupportedOperationException will be thrown, etcetera. If your 3rd party routine's docs don't state anything, then it does not apply (or it is badly documented).
The 'second' case (laziness) is hopefully not the case either - that would mean the programmer of it did a bad job.
The third case should also be documented.
That leaves the 4th case, which could happen and won't be documented. You have some control over this, though.
CONCLUSION: Well written libraries will not be throwing undocumented RuntimeExceptions that you didn't expect (i.e. where you aren't the direct cause of it by handing weird objects or things that don't fit clearly documented specs)

Does the JVM optimization being applied to a function that doesn't have try-catch bug throws a exception?

There is a question What is the difference between try-catch and throws Exception in terms of performance?
.
A follow-up question is "Does the JVM optimization being applied to a function that doesn't have try-catch bug throws a exception?". For example, all methods throw their exceptions and the main method has a try-catch to surround all methods and codes. In this case, according to "Effective Java":
Placing code inside a try-catch block inhibits certain optimizations that modern JVM implementations might otherwise perform.
JVM won't do some optimization for the code in the main method. The question is: dose the JVM optimize the code in those methods who throw exceptions?
If you mean the throws clause, then definitely not. Note that all methods sort of have an "invisible throws RuntimeException, Error clause", i.e., they may throw something.
Note also, that there's nothing like checked exceptions on the JVM level, it's a pure Java source feature which doesn't exist in the bytecode (and there are many other languages running on the JVM and having no checked exceptions; AFAIK Java is the only experiment).
Actually throwing exceptions is expensive, but basically any method can throw some. Even an empty method can in theory throw a StackOverflowError. It only gets expensive, when an exception actually happens.
For a try-catch block, there's just an entry somewhere which gets consulted, when an exception gets actually thrown, otherwise it doesn't get used. It may prevent some optimizations, which would make it impossible to use this information, or not; the JVM gets better and better.
Anyway, adding a throws clause has no performance impact and it's the right thing most of the time.

How to find potential unchecked exceptions in Java?

In accordance with the Java specification, The Java compiler verifies automatically that all checked exceptions are caught, based on "throw" statements and method signatures, and ignores unchecked exceptions.
However, sometimes it would be useful for the developer to find out what unchecked exceptions can be thrown, for instance some 3rd party code might throw unchecked exceptions in situations where the developer would tend to expect a checked exception (like Long.parseLong). Or a developer might throw an unchecked exception as a placeholder for a future checked exception and forget to replace it.
In these examples, it is theoretically possible to find these uncaught unchecked exception. In the first case, the signature of Long.parseLong indicates that it throws NumberFormatException, and in the second case, the source code is available, so the compiler knows what unchecked exceptions are thrown.
My question is: is there a tool that can report these cases? Or maybe a way to let the Java compiler treat temporarily unchecked exceptions are checked exceptions? That would be very useful to verify manually and fix potential bugs that would otherwise cause a crash of the whole thread or application at runtime.
EDIT: after some answers, I have to underline that my goal is not to find the exhaustive list of unchecked exceptions possible in the system, but potential bugs due to unchecked exceptions. I think it boils down to the two cases:
a method's signature indicates that it throws an unchecked exception, and the caller doesn't catch it
a method's body throws explicitly unchecked exceptions, and the caller doesn't catch them
Yes you can write a static analysis to do this. I've done something similar myself and wrote mine in a program analysis tool called Atlas. Here: https://github.com/EnSoftCorp/java-toolbox-commons/.../ThrowableAnalysis.java is some code that might be helpful for what you need, it statically computes matches for throw sites and potential catch sites in a piece of software (conservatively in that it does not consider path feasibility). For your case you are interested in throw sites that do not have a corresponding catch block.
Here are the important bits of the analysis.
All exceptions checked or unchecked must extend Throwable. It sounds like you are only interested in "unchecked" throwables so you should consider classes that directly extend or are children of a class that extends Error or RuntimeException.
In the Atlas Shell you could write the following queries to find all the unchecked throwables.
var supertypeEdges = Common.universe().edgesTaggedWithAny(XCSG.Supertype)
var errors = supertypeEdges.reverse(Common.typeSelect("java.lang", "Error"))
var uncheckedExceptions = supertypeEdges.reverse(Common.typeSelect("java.lang", "RuntimeException"))
show(errors.union(uncheckedExceptions))
Any exception that can be caught at runtime (checked or unchecked) must have a corresponding "throw" site. While a thrown checked exception must be declared in a method signature, it is not required to be declared for a thrown unchecked exception. However this isn't really that important since we can detect all thrown unchecked exceptions simply by looking at the type hierarchy as we discussed in step 1.
To match the throw site with the corresponding catch block we must remember that a thrown exception propogates back up the call stack until it is caught (or crashes the program when it is not caught by the main method or thread entry point). To do this analysis you need a call graph (the more precise the call graph is the more accurate your analysis will be here). For each throw of an unchecked exception type step backwards along the call graph to the callsite of the method that could throw the unchecked exception. Check if the callsite is contained within a try block (or has a trap region if you are analyzing bytecode). If it is you must check the compatibility of the catch blocks/trap regions and determine if the exception will be caught. If the exception is not caught repeat the process stepping backwards along the call graph to each callsite until the exception is caught or there is no possible catch block.
Using the ThrowableAnalysis code I shared earlier you could bring it all together to find each uncaught thrown unchecked throwable types.
public class Analysis {
// execute show(Analysis.run()) on the Atlas shell
public static Q run(){
Q supertypeEdges = Common.universe().edgesTaggedWithAny(XCSG.Supertype);
Q errors = supertypeEdges.reverse(Common.typeSelect("java.lang", "Error"));
Q uncheckedExceptions = supertypeEdges.reverse(Common.typeSelect("java.lang", "RuntimeException"));
Q typeOfEdges = Common.universe().edgesTaggedWithAny(XCSG.TypeOf);
Q thrownUncheckedThrowables = typeOfEdges.predecessors(errors.union(uncheckedExceptions)).nodesTaggedWithAny(XCSG.ThrownValue);
AtlasSet<Node> uncaughtThrownUncheckedThrowables = new AtlasHashSet<Node>();
for(Node thrownUncheckedThrowable : thrownUncheckedThrowables.eval().nodes()){
if(ThrowableAnalysis.findCatchForThrows(Common.toQ(thrownUncheckedThrowable)).eval().nodes().isEmpty()){
uncaughtThrownUncheckedThrowables.add(thrownUncheckedThrowable);
}
}
Q uncaughtThrownUncheckedThrowableMethods = Common.toQ(uncaughtThrownUncheckedThrowables).containers().nodesTaggedWithAny(XCSG.Method);
Q callEdges = Common.universe().edgesTaggedWithAny(XCSG.Call);
Q rootMethods = callEdges.reverse(uncaughtThrownUncheckedThrowableMethods).roots();
Q callChainToUncaughtThrowables = callEdges.between(rootMethods, uncaughtThrownUncheckedThrowableMethods);
return callChainToUncaughtThrowables.union(Common.toQ(uncaughtThrownUncheckedThrowables));
}
}
Here's a screenshot of the result of running this code on the following test case.
public class Test {
public static void main(String[] args) {
foo();
}
private static void foo(){
throw new Pig("Pigs can fly!");
}
public static class Pig extends RuntimeException {
public Pig(String message){
super(message);
}
}
}
Important Caveats: You must consider whether or not to do whole program analysis here. If you only analyze your code and not the full JDK (several million lines of code) then you will only detect uncaught runtime exceptions which originate inside your application. For example you would not catch "test".substring(0,10) which throws an out of bounds exception inside the substring method declared in the String class in the JDK. While Atlas supports partial or whole program analysis using Java source or bytecode and can scale up to the full JDK, you would need to allocate about an hour of pre-processing time and 20 gigabytes more memory if you plan to include the full JDK.
There is an Intellij plugin that can help you discover unchecked exceptions.
You can customize the search process to include/exclude libraries when searching for them.
https://plugins.jetbrains.com/plugin/8157?pr=
My question is: is there a tool that can report these cases?
AFAIK, no.
Or maybe a way to let the Java compiler treat temporarily unchecked exceptions are checked exceptions?
AFAIK, no.
While tools like this are theoretically possible (with some caveats1), they would be close to useless in practice. If you rely solely on local analysis of methods, most ordinary Java would be flagged as potentially throwing a wide range of unchecked exceptions. Some of these could be excluded with some simple non-local analysis, but that would be nowhere like enough to avoid excessive "false positives".
IMO, there is no practical way to eliminate all runtime exceptions.
What you should be doing is to combining the following practice in order to reduce the number of bugs (including unexpected runtime exceptions) that make it into production code
Thorough and methodical testing; e.g. by developing automated unit and system test-suites, and using coverage tools to help you identify codepaths that have not been tested.
Use of static analysis tools like PMD and FindBugs that can detect certain classes of problem. You can help these and similar tools by using annotations like #NotNull.
Code reviews.
Following good coding practice, especially when developing multi-threaded code.
But note that these practices are expensive, and they don't eliminate all bugs.
Some of the other answers seem to be suggestion that you should catch all exceptions (e.g. Exception, RuntimeException or even Throwable) as a way of avoiding crashes.
This is misguided. Yes, you can "catch them all" (this is called Pokemon exception handling!) but you can't safely recover from an arbitrary unexpected exception. In general, the only entirely safe thing to do when you get an unexpected exception is to bail out.
1 - These caveats are: 1) the analyser needs to be aware of the Java language constructs that can throw unchecked exceptions implicitly; e.g. instance method call can throw a NPE, a new can throw an OOOME, etc. 2) you need to analyse all library methods used by your code, including 3rd-party libraries, 3) Java exceptions could be thrown from native code, and 4) things involving static and "bytecode engineering" need to be considered.
There is no way to get a list of possible unchecked exceptions. Since they are not declared anywhere (they are created on the fly) it's just not possible without a pretty specific code analyzer tool--and even then it might not catch some from compiled library classes.
For examples of tricky things to predict consider anything that allocates memory can throw an out of memory exception and you could even instantiate an exception reflectively which would be pretty much impossible to find with ANY static analysis tools.
If you are really really paranoid you could catch RuntimeException, that should get all unchecked exceptions that you would want to deal with--it's not a recommended tactic but can prevent your program from failing from some unknown/unseen future bug.
It's not possible to find unchecked exceptions in many cases, or you might as well end up with a very long list of possible exceptions that could occur.
When is it not possible to find unchecked exceptions? Assume you want to call a method of an interface. One implementation might throw certain unchecked exceptions, others won't. The compiler can't know because it's only known at runtime.
Why could you end up with a very long list of possible exceptions? Well, pretty much every method might throw NullPointerException, in case you provide null parameters which are not explicitly checked. If they are checked, there's probably an IllegalArgumentException instead. Furthermore, every single method which this method calls might also throw different unchecked exceptions, which would have to be added to the list. You could run into a ClassNotFoundError or OutOfMemoryError anytime, which would also have to be added to that list...
Image a simple method like
public Foo bar(String input) {
return new Foo(input.charAt(0));
}
Alone that method could throw at least a NullPointerException or some OutOfBounds thing.
And the catch is: in order to see "all" potential exceptions, your tool would have to check each and any line of code (compiled or source) that goes into your applications.
I don't see how this could in any way be "manageable".
And it gets worse, what if
public Foo(char whatever) {
String klazz = ... god knows
throw (RuntimeException) Class.forName(klazz).newInstance();
Of course, that would need some try/catch for the checked exceptions that the reflection code has; but the point is: understand the whole universe of potential exceptions might end up in some "pretty huge map" drawn for you. With so many paths/branches in it that you never find the 0.001% of interesting paths in there.

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.

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