Catching exceptions properly - java

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.

Related

Java API and checked/unchecked exceptions confusion

The question about checked and unchecked exceptions was raised here and on other websites million times, but I'm still confused with so different answers.
In many answers and articles we can read general statements like:
Unchecked runtime exceptions represent conditions that, generally
speaking, reflect errors in your program's logic and cannot be
reasonably recovered from at run time.
and for checked exceptions
represent invalid conditions in areas outside the immediate control of
the program (invalid user input, database problems, network outages,
absent files)
both quotes are from http://www.javapractices.com/topic/TopicAction.do?Id=129 and are cited many times.
We can read similar statements on oracle website:
Runtime exceptions represent problems that are the result of a
programming problem, and as such, the API client code cannot
reasonably be expected to recover from them or to handle them in any
way
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Lets take simple example with reading Number with Scanner:
Scanner sc = new Scanner(System.in);
int userInput = sc.nextInt();
System.out.println(userInput);
nextInt() throws InputMismatchException when I type i.e. "asdf" instead of int. InputMismatchException is RuntimeException but according to statements above this is the first example of checked exceptions "invalid user input".
When I look at checked exceptions I am even more confused. For example NPE vs FileNotFoundException - both can be prevented by simple if-else, so why first one is unchecked and second is checked?
Oracle website has bottom line guideline:
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.
So according to that I can recover from FileNotFoundException or IOException but I can't from NPE or ArrayIndexOutOfBoundsException? This makes no sense.
Maybe someone has better explanation to this with some better example?
To be very simple and factual :
an unchecked exception (Runtime class and children) conveys an unexpected exception.
In general, the caller should not know how to handle it and doesn't wait for it in any of his scenarios.
a checked exception conveys a exception that you may consider as a "normal" exception and the caller know how to handle it. It is probably not the nominal case for him but the caller knows that it could happen and should prepare himself to handle it.
In your example :
nextInt() throws InputMismatchException when I type i.e. "asdf"
instead of int. InputMismatchException is RuntimeException but
according to statements above this is the first example of checked
exceptions "invalid user input".
When a method calls nextInt() the caller waits for a int value. It is the excepted scenario. If it was not the case the user would do rather : next() to retrieve a String object and try then to convert it by something that suits.
When you invoke nextInt(), the caller waits for an int as he has requested it. Force him to handle InputMismatchException as a checked Exceptionwould be counter-intuitive.
So according to that I can recover from FileNotFoundException or
IOException but I can't from NPE or ArrayIndexOutOfBoundsException?
This makes no sense.
I think JDK Exceptions as FileNotFoundException or IOException are special cases. They are probably checked not necessarily because the client of these classes waits for that the file is not found or the stream generates some exceptions during reading or writing but rather because a stream may be in a not suitable state and consequently raises exception for many external reasons (file locked, lack of right, file moved to another place or to a not reachable network and so for...).
A file that generates an exception is probably considered as something that is important to handle.
So, the JDK specification prefers that the caller handles it explicitly.
Besides, before the arrival of the try-with-resources statement, the caller should explicitly close streams in case of exceptions.
NPE and ArrayIndexOutOfBoundsException are generally programming errors. The application cannot do a processing to recover specifically errors which it doesn't know the existence. So why make them checked ?
every single exception may or may not be recoverable in your app. it always depends on the context. if some object is null and you get NPE (unchecked) it may result in an empty expression language expression (so in this particular context, this situation is perfectly recoverable). on the other hand, you may get IOException (checked) which is irrecoverable because your web application can't connect to database and therefore is useless in context of this particular web application.
Maybe someone has better explanation to this
there is a better explanation: making checked and unchecked exception was simply a wrong design decision of language authors. and it decision won't be changed as long as java remains backward compatible.
so just:
ignore this artificial division (as other modern languages decided to do)
when design your api always use unchecked
when working with checked exception, wrap them in unchecked deep down the call stack (your life will be easier)
when calling a method always think/check what exceptions it may throw (checked or unchecked) and decide for every one of them if you should handle it or rethrow/pass through

Exceptions in java, rethrown [duplicate]

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.

Try-catch: is this acceptable practice?

We have received Java code from a software supplier. It contains a lot of try-catch blocks with nothing in the catch part. They're all over the place. Example:
try {
spaceBlock.enable(LindsayModel);
} catch (Exception e) {
}
My questions are: Is the above acceptable practice? If so, when? Or should I just go ahead and remove all of these "bogus" try and catch statements?
To me this looks like terrible practice, but I'm not experienced enough in Java to tell for sure. Why catch errors if you're not going to do anything with them? Seems to me, you would only do that if you were confident that an exception would be of absolutely no consequence and you don't care if one occurs. However, this is not really the case in our particular application.
EDIT To give some context: We bought a Java-scriptable product from the supplier. Alongside the product, they provided a large proof-of-concept script tailored to our needs. This script came "free of charge" (though we wouldn't have bought the product if it hadn't come with the script) and it "works". But the script is a real pain to build upon, due to many things that even I as a Java novice recognise as awful practice, one instance being this bogus try-catch business.
This is indeed terrible practice. Especially the catching of Exception rather than something specific gives off a horrible smell - even a NullPointerException will be swallowed. Even if it is assured that a particular thrown exception is of no real consequence, one should always log it at the very least:
try {
// code
}
catch (MyInconsequentialException mie) {
// tune level for this logger in logging config file if this is too spammy
MY_LOGGER.warning("Caught an inconsequential exception.", mie);
}
However it is unlikely an exception is completely meaningless in this situation. I recommend researching exactly what exception(s) the application's code is intending to swallow here, and what they would really mean for the execution.
One important distinction is whether the try/catches are used to swallow checked exceptions. If this is the case, it probably indicates extreme apathy on the programmer's part - somebody just wanted his/her code to compile. At the least, the code should be amended:
try {
// code
}
catch (SpecificCheckedException sce) {
// make sure there is exception logging done farther up
throw new RuntimeException(sce);
}
This will rethrow the exception wrapped in an unchecked RuntimeException, effectively allowing the code to compile. Even this can be considered a bandaid however - best practice for checked exceptions is to handle them on an individual basis, either in the current method or farther up by adding throws SpecificCheckedException to the method signature.
As #Tom Hawtin mentioned, new Error(sce) can be used instead of new RuntimeException(sce) in order to circumvent any additional Exception catches farther up, which makes sense for something that isn't expected to be thrown.
If the try/catch is not being used to swallow checked exceptions, it is equally dangerous and should simply be removed.
Terrible, indeed. Swallowing an exception like this can be dangerous. How will you know if something bad has happened?
I'd feel better if the vendor wrote comments to document and acknowledge it ("We know what we're doing"). I'd feel even better if there was a strategy apparent in the code to deal with the consequences. Wrap it in a RuntimeException and rethrow; set the return value to an appropriate value. Anything!
"All over the place"? Are there multiple try/catch blocks littering the code? Personally, I don't like that idiom. I prefer one per method.
Maybe you should find a new vendor or write your own.
try {
meshContinuum.enable(MeshingModel);
} catch (Exception e) {
}
This looks like unfinished code. If the enable method throws an Exception then it will be caught and swallowed by the code. If it doesn't then it does not make sense to try to catch a non occuring exception.
Check to see the methods and where their signatures are not followed by throws exceptionName, then remove the empty try-catch statements from the places they are called.
You can theoretically put try-catch around any statement. The compiler will not complain about it. It does not make sense though, since this way one may hide real exceptions.
You can see this as a sign of bad code quality. You should probably be prepared to run into problems of different type too.
It's not the best:
It hides evidence of the exception so debugging is harder
It may cause features to fail silently
It suggests that the author might actually have wanted to handle the exception but never got around to it
So, there may be cases where this is OK, such as an exception that really is of no consequence (the case that comes to mind is Python's mkdirs, which throws an exception if the directory already exists), but usually, it's not so great.
Unfortunately you cannot just remove it, because it the try block throws a checked exception then it will have to be declared in the throws clause of the method. The callers of the method will then have to catch it (but not if the callers also have this catch (Exception e) {} abomination).
As an alternative, consider replacing it with
try {
meshContinuum.enable(MeshingModel);
} catch (Exception e) {
throw (e instanceof RuntimeException) ? (RuntimeException) e : new RuntimeException(e);
}
Since RuntimeException (and classes that extend it) are unchecked exceptions they do not need to be declared in the throws clause.
What did your contract with the supplier specify? If what they wrote, bad practice and all, meets the spec then they will charge you for a rewrite.
Better to specify a set of tests that will enter many or all of those try-catch blocks and hence fail. If the tests fail you have a better argument to make them fix their terrible code.
Horrible idea on the face of it, totally depends on what you're actually calling. Usually it's done out of laziness or habituated bad practices.
Actually ... not so fast.
There are legitimate cases for ignoring an exception.
Suppose that an exception has happened already, and we're already in a catch(). While in the catch(), we want to make best effort to clean up (which could fail, too). Which exception to return?? The original one, of course. The code looks like this:
try {
something-that-throws();
} catch(Exception e) {
try {
something-else-that-throws();
} catch(Exception e1) {}
throw e;
}
When we really don't care whether an operation succeeds, but (unfortunately) the operation's author throws an exception if a failure occurs.
if (reinitialize) {
try {
FileUtils.forceDelete(sandboxFile); // delete directory if it's there
} catch(Exception e) {}
}
The above saves a rather tortured attempt to see if sandboxFile actually exists before deleting it anyway.

Java API Design: NumberFormatException for Method that Parses a Semi-Numeric String?

I'm making a library that contains a few methods for parsing string dates and times. I am having difficulty deciding what exception those methods should throw when the string argument isn't parseable. I'm considering several options:
1. java.lang.IllegalArgumentException - an invalid string is clearly an illegal argument, but, to me, IllegalArgumentException typically means programming error, and it's rare to want to do an explicit try catch for one. I think string parsing is often for external input and is more of a special case that deserves special treatment. If, say, you had a big block of code that parsed user input and did something else with it, you might want to wrap that code in a try catch block so you could handle the case of the user input containing an invalid string. But catching IllegalArgumentException wouldn't be great for pinpointing invalid user input, because most likely there'd be multiple places in your code that it could be thrown from (not just the user-input parsing).
2. java.lang.NumberFormatException - it's thrown by Integer.parseInt(String) and other similar parsing methods in java.lang. So most Java developers are familiar with it being the exception to catch when you're trying to parse a string that may or may not be valid (e.g. user input). But it's got "Number" in its name, so I'm not sure it really fits with things like dates and times which are numeric in a sense, but conceptually different in my mind. If only it was called "FormatException"...
3. java.text.ParseException - not really an option because it's checked. I want unchecked for this.
4. A custom exception - this gets around the downsides of IllegalArgumentException and NumberFormatException, and it could extend IllegalArgumentException too. But I don't think it's a good idea to add exceptions to a library unless they're really needed. Quoting Josh Bloch, "If in doubt, leave it out". (Also, in my case, for a package that parses dates and times it's quite hard to name such an exception: "DateFormatException", "TimeFormatException", "CalendricalFormatException" (like JSR 310) - none seem ideal to me when applied to methods that parse dates, times, date-times etc. And I think it would be silly to create multiple exceptions in a single package if they were all just used to identify unparseable strings.)
So which option do you think makes most sense?
NB There are good reasons for me to not wanting to use java.util.Date or Joda Time, or JSR 310, so no need to suggest those. Plus I think it would be good if this question was kept fairly general, since this must be an issue that other people designing APIs have struggled with. Dates and times could just as well be IP addresses, or URLs, or any other kind of information that has string formats that need parsing.
Precedents Set by Other Libraries
Just a few examples I found:
java.sql.Timestamp.valueOf(String) throws IllegalArgumentException
java.util.Date.parse(String) throws IllegalArgumentException (deprecated method, and the exception isn't declared, but you can see it in the source)
java.util.UUID.fromString(String) throws IllegalArgumentException
org.apache.axis.types.Time(String) throws NumberFormatException (also Day class in Apache Axis)
org.apache.tools.ant.util.DeweyDecimal(String) throws NumberFormatException
com.google.gdata.data.DateTime.parseDateTime(String) throws NumberFormatException
java.lang.Package.isCompatibleWith(String versionString) throws NumberFormatException (in Java 7, this takes a string version number with dots - kind of like a date or a time in a sense)
I'm sure there are lots of packages that use a custom exception, so I doubt there's much point in giving examples of those.
I would have suggested IllegalFormatException as base class (which inherits from IllegalArgumentException, but unfortunately the sole Constructor is Package-protected, so I'd probably use
IllegalArgumentException for a
small API (a few methods)
your own Class Hierarchy that inherits from IllegalArgumentException otherwise.
In any case, I would use IllegalArgumentException as base class.
In one of my previous projects, the guideline was to only throw RuntimeExceptions that inherit from
IllegalStateException
IllegalArgumentException
UnsupportedOperationException
Although this isn't an official dogma, I'd call it a good practice. All three of these are simple and self-descriptive.
I would opt for ParseException, because that's what DateFormat.parse throws. Thus it has the advantage you mention in 2., programmers being familiar with it. But since you want unchecked, I guess this is not an option. If forced to go for unchecked, I'll opt for 4.
For this question, it is a matter of taste. In my opinion, I would not throw exception but handle that in return. The reason is that user cannot do anything in exception handler if the input was wrong. So these type of errors can be easily handled by checking the return code. Exceptions are heavy and dont bring extra value.
I'm currently leaning in favour of using NumberFormatException. I was thinking plain old IllegalArgumentException but it became clear to me that that wasn't ideal when I wrote a little code like:
try {
final Day day = Day.fromString(userInputString);
someMethodThatCouldAlsoThrowIllegalArgumentException(day);
} catch (IllegalArgumentException e) {
ui.showWarningMessage("Invalid date: " + userInputString);
}
Assuming you parse a valid Day, you'll want to do something with it. And it's very likely that the methods you'd pass it to would throw an IllegalArgumentException if they received an invalid parameter (i.e. a programming error rather than a user error). In code like the above example you'd want to be careful not to confuse a programming error for invalid user input, so, to be on the safe side, you'd need something messy like a null variable defined before the try/catch block, and a check for null after it.
Swap IllegalArgumentException for NumberFormatException or a custom exception and the problem goes away.
Having seen that JDK 1.7's java.lang.Package.isCompatibleWith(String versionNo) uses NumberFormatException for a method that parses a version number (a semi-numeric string like "1.6.1.32"), I'm thinking that this might also be the sensible choice for methods that parse things like dates and times.
NumberFormatException is not exactly ideal for parsing strings that are only semi-numeric, but perhaps it's the best option when you don't want to clutter an API with a custom exception that isn't really needed. If they're doing it in java.lang, then perhaps that makes it the Java way of doing things by definition...
I'm hoping it catches on :)

Throws or try-catch

What is the general rule of thumb when deciding whether to add a throws clause to a method or using a try-catch?
From what I've read myself, the throws should be used when the caller has broken their end of the contract (passed object) and the try-catch should be used when an exception takes place during an operation that is being carried out inside the method. Is this correct? If so, what should be done on the callers side?
P.S: Searched through Google and SO but would like a clear answer on this one.
catch an exception only if you can handle it in a meaningful way
declare throwing the exception upward if it is to be handled by the consumer of the current method
throw exceptions if they are caused by the input parameters (but these are more often unchecked)
In general, a method should throw an exception to its caller when it can't handle the associated problem locally. E.g. if the method is supposed to read from a file with the given path, IOExceptions can't be handled locally in a sensible way. Same applies for invalid input, adding that my personal choice would be to throw an unchecked exception like IllegalArgumentException in this case.
And it should catch an exception from a called method it if:
it is something that can be handled locally (e.g. trying to convert an input string to a number, and if the conversion fails, it is entirely valid to return a default value instead),
or it should not be thrown (e.g. if the exception is coming from an implementation-specific lower layer, whose implementation details should not be visible to the caller — for example I don't want to show that my DAO uses Hibernate for persisting my entities, so I catch all HibernateExceptions locally and convert them into my own exception types).
Here's the way I use it:
Throws:
You just want the code to stop when
an error occurs.
Good with methods that are prone to
errors if certain prerequisites are
not met.
Try-Catch:
When you want to have the program
behave differently with different
errors.
Great if you want to provide
meaningful errors to end users.
I know a lot of people who always use Throws because it's cleaner, but there's just not nearly as much control.
My personnal rule of thumb for that is simple :
Can I handle it in a meaningful way (added from comment)? So put code in try/catch. By handle it, I mean be able to inform the user/recover from error or, in a broader sense, be able to understand how this exception affects the execution of my code.
Elsewhere, throw it away
Note : this replys is now a community wiki, feel free to add more info in.
The decision to add a try-catch or a throws clause to your methods depends on "how you want (or have) to handle your exception".
How to handle an exception is a wide and far from trivial question to answer. It involves specially the decision of where to handle the exception and what actions to implement within the catch block. In fact, how to handle an exception should be a global design decision.
So answering your questions, there is no rule of thumb.
You have to decide where you want to handle your exception and that decision is usually very specific to your domain and application requirements.
If the method where the exception got raised has a sufficent amount of information to deal with it then it should catch, generate useful information about what happened and what data was being processed.
A method should only throws an exception if it can make reasonable guarantees surrounding the state of the object, any parameters passed to the method, and any other objects the method acts upon. For example, a method which is supposed to retrieve from a collection an item which the caller expects to be contained therein might throws a checked exception if the item which was expected to exist in the collection, doesn't. A caller which catches that exception should expect that the collection does not contain the item in question.
Note that while Java will allow checked exceptions to bubble up through a method which is declared as throwing exceptions of the appropriate types, such usage should generally be considered an anti-pattern. Imagine, for example, that some method LookAtSky() is declared as calling FullMoonException, and is expected to throw it when the Moon is full; imagine further, that LookAtSky() calls ExamineJupiter(), which is also declared as throws FullMoonException. If a FullMoonException were thrown by ExamineJupiter(), and if LookAtSky() didn't catch it and either handle it or wrap it in some other exception type, the code which called LookAtSky would assume the exception was a result of Earth's moon being full; it would have no clue that one of Jupiter's moons might be the culprit.
Exceptions which a caller may expect to handle (including essentially all checked exceptions) should only be allowed to percolate up through a method if the exception will mean the same thing to the method's caller as it meant to the called method. If code calls a method which is declared as throwing some checked exception, but the caller isn't expecting it to ever throw that exception in practice (e.g. because it thinks it pre-validated method arguments), the checked exception should be caught and wrapped in some unchecked exception type. If the caller isn't expecting the exception to be thrown, the caller can't be expecting it to have any particular meaning.
When to use what. I searched a lot about this.
There is no hard and fast rule.
"But As a developer, Checked exceptions must be included in a throws clause of the method. This is necessary for the compiler to know which exceptions to check.
By convention, unchecked exceptions should not be included in a throws clause.
Including them is considered to be poor programming practice. The compiler treats them as comments, and does no checking on them."
Source : SCJP 6 book by Kathy Sierra
I ll make it simple for you.
Use throws when you think that the called method is not responsible for the exception (e.g., Invalid parameters from the caller method, item to be searched, fetched not available in the collections or fetch datalist).
Use try catch block(handle the exception in the called method) when you think that your functionality in the called method may result in some exception
If you use a try catch, when the exception occurs, the remaining codes would be still executed.
If you indicate the method to throw the exception, then when the exception occurs, the code would stop being executed right away.
try-catch pair is used when you want to provide customise behaviour, in case if exception occurs.....in other words...you have a solution of your problem (exception occurrence) as per your programme requirements.....
But throws is used when you don't have any specific solution regarding the exception occurrence case...you just don't want to get abnormal termination of your programme....
Hope it is correct :-)

Categories

Resources