What is the difference between try-catch and throw clause. When to use these?
Please let me know .
The try block will execute a sensitive code which can throw exceptions
The catch block will be used whenever an exception (of the type caught) is thrown in the try block
The finally block is called in every case after the try/catch blocks. Even if the exception isn't caught or if your previous blocks break the execution flow.
The throw keyword will allow you to throw an exception (which will break the execution flow and can be caught in a catch block).
The throws keyword in the method prototype is used to specify that your method might throw exceptions of the specified type. It's useful when you have checked exception (exception that you have to handle) that you don't want to catch in your current method.
Resources :
oracle.com - Lesson: Exceptions
On another note, you should really accept some answers. If anyone encounter the same problems as you and find your questions, he/she will be happy to directly see the right answer to the question.
If you execute the following example, you will know the difference between a Throw and a Catch block.
In general terms:
The catch block will handle the Exception
throws will pass the error to his caller.
In the following example, the error occurs in the throwsMethod() but it is handled in the catchMethod().
public class CatchThrow {
private static void throwsMethod() throws NumberFormatException {
String intNumber = "5A";
Integer.parseInt(intNumber);
}
private static void catchMethod() {
try {
throwsMethod();
} catch (NumberFormatException e) {
System.out.println("Convertion Error");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
catchMethod();
}
}
Try/catch and throw clause are for different purposes. So they are not alternative to each other but they are complementary.
If you have throw some checked exception in your code, it should be inside some try/catch in codes calling hierarchy.
Conversely, you need try/catch block only if there is some throw clause inside the code (your code or the API call) that throws checked exception.
Sometimes, you may want to throw exception if particular condition occurred which you want to handle in calling code block and in some cases handle some exception catch block and throw a same or different exception again to handle in calling block.
All these keywords try, catch and throw are related to the exception handling concept in java. An exception is an event that occurs during the execution of programs. Exception disrupts the normal flow of an application. Exception handling is a mechanism used to handle the exception so that the normal flow of application can be maintained. Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.
For more detail visit Java tutorial for beginners.
Others have already given thorough answers, but if you're looking for even more information, the Oracle Java tutorials are always a good resource. Here's the Java tutorial for Exceptions, which covers all of your questions in great detail; https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html
try block contains set of statements where an exception can occur.
catch block will be used to used to handle the exception that occur with in try block. A try block is always followed by a catch block and we can have multiple catch blocks.
finally block is executed after catch block. We basically use it to put some common code when there are multiple catch blocks. Even if there is an exception or not finally block gets executed.
throw keyword will allow you to throw an exception and it is used to transfer control from try block to catch block.
throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.
// Java program to demonstrate working of throws, throw, try, catch and finally.
public class MyExample {
static void myMethod() throws IllegalAccessException
{
System.out.println("Inside myMethod().");
throw new IllegalAccessException("demo");
}
// This is a caller function
public static void main(String args[])
{
try {
myMethod();
}
catch (IllegalAccessException e) {
System.out.println("exception caught in main method.");
}
finally(){
System.out.println("I am in final block.");
}
}
}
Output:
Inside myMethod().
exception caught in main method.
I am in final block.
In my limited experience with the following details.throws is a declaration that declares multiple exceptions that may occur but do not necessarily occur,
throw is an action that can throw only one exception, typically a non-runtime exception,
try catch is a block that catches exceptions that can be handled when an exception occurs in a method,this exception can be thrown.An exception can be understood as a responsibility that should be taken care of by the behavior that caused the exception, rather than by its upper callers.
I hope my answer will help you
try - Add sensitive code
catch - to handle exception
finally - always executed whether exception caught or not. Associated with try -catch. Used to close the resource which we opened in try block
throw - To handover our created exception to JVM manually. Used to throw customized exception
throws - To delegate the responsibility of exception handling to caller method or main method.
Related
New Java programmers frequently encounter errors phrased like this:
"error: unreported exception <XXX>; must be caught or declared to be thrown"
where XXX is the name of some exception class.
Please explain:
What the compilation error message is saying,
the Java concepts behind this error, and
how to fix it.
First things first. This a compilation error not a exception. You should see it at compile time.
If you see it in a runtime exception message, that's probably because you are running some code with compilation errors in it. Go back and fix the compilation errors. Then find and set the setting in your IDE that prevents it generating ".class" files for source code with compilation errors. (Save yourself future pain.)
The short answer to the question is:
The error message is saying that the statement with this error is throwing (or propagating) a checked exception, and the exception (the XXX) is not being dealt with properly.
The solution is to deal with the exception by either:
catching and handling it with a try ... catch statement, or
declaring that the enclosing method or constructor throws it1.
1 - There are some edge-cases where you can't do that. Read the rest of the answer!
Checked versus unchecked exceptions
In Java, exceptions are represented by classes that descend from the java.lang.Throwable class. Exceptions are divided into two categories:
Checked exceptions are Throwable, and Exception and its subclasses, apart from RuntimeException and its subclasses.
Unchecked exceptions are all other exceptions; i.e. Error and its subclasses, and RuntimeException and its subclasses.
(In the above, "subclasses" includes by direct and indirect subclasses.)
The distinction between checked and unchecked exceptions is that checked exceptions must be "dealt with" within the enclosing method or constructor that they occur, but unchecked exceptions need not be dealt with.
(Q: How do you know if an exception is checked or not? A: Find the javadoc for the exception's class, and look at its parent classes.)
How do you deal with a (checked) exception
From the Java language perspective, there are two ways to deal with an exception that will "satisfy" the compiler:
You can catch the exception in a try ... catch statement. For example:
public void doThings() {
try {
// do some things
if (someFlag) {
throw new IOException("cannot read something");
}
// do more things
} catch (IOException ex) {
// deal with it <<<=== HERE
}
}
In the above, we put the statement that throws the (checked) IOException in the body of the try. Then we wrote a catch clause to catch the exception. (We could catch a superclass of IOException ... but in this case that would be Exception and catching Exception is a bad idea.)
You can declare that the enclosing method or constructor throws the exception
public void doThings() throws IOException {
// do some things
if (someFlag) {
throw new IOException("cannot read something");
}
// do more things
}
In the above we have declared that doThings() throws IOException. That means that any code that calls the doThings() method has to deal with the exception. In short, we are passing the problem of dealing with the exception to the caller.
Which of these things is the correct thing to do?
It depends on the context. However, a general principle is that you should deal with exceptions at a level in the code where you are able to deal with them appropriately. And that in turn depends on what the exception handling code is going to do (at HERE). Can it recover? Can it abandon the current request? Should it halt the application?
Solving the problem
To recap. The compilation error means that:
your code has thrown a checked exception, or called some method or constructor that throws the checked exception, and
it has not dealt with the exception by catching it or by declaring it as required by the Java language.
Your solution process should be:
Understand what the exception means, and why it could be thrown.
Based on 1, decide on the correct way to deal with it.
Based on 2, make the relevant changes to your code.
Example: throwing and catching in the same method
Consider the following example from this Q&A
public class Main {
static void t() throws IllegalAccessException {
try {
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
System.out.println(e);
}
}
public static void main(String[] args){
t();
System.out.println("hello");
}
}
If you have been following what we have said so far, you will realise that the t() will give the "unreported exception" compilation error. In this case, the mistake is that t has been declared as throws IllegalAccessException. In fact the exception does not propagate, because it has been caught within the method that threw it.
The fix in this example will be to remove the throws IllegalAccessException.
The mini-lesson here is that throws IllegalAccessException is the method saying that the caller should expect the exception to propagate. It doesn't actually mean that it will propagate. And the flip-side is that if you don't expect the exception to propagate (e.g. because it wasn't thrown, or because it was caught and not rethrown) then the method's signature shouldn't say it is thrown!
Bad practice with exceptions
There are a couple of things that you should avoid doing:
Don't catch Exception (or Throwable) as a short cut for catching a list of exceptions. If you do that, you are liable catch things that you don't expect (like an unchecked NullPointerException) and then attempt to recover when you shouldn't.
Don't declare a method as throws Exception. That forces the called to deal with (potentially) any checked exception ... which is a nightmare.
Don't squash exceptions. For example
try {
...
} catch (NullPointerException ex) {
// It never happens ... ignoring this
}
If you squash exceptions, you are liable to make the runtime errors that triggered them much harder to diagnose. You are destroying the evidence.
Note: just believing that the exception never happens (per the comment) doesn't necessarily make it a fact.
Edge case: static initializers
There some situations where dealing with checked exceptions is a problem. One particular case is checked exceptions in static initializers. For example:
private static final FileInputStream input = new FileInputStream("foo.txt");
The FileInputStream is declared as throws FileNotFoundException ... which is a checked exception. But since the above is a field declaration, the syntax of the Java language, won't let us put the declaration inside a try ... catch. And there is no appropriate (enclosing) method or constructor ... because this code is run when the class is initialized.
One solution is to use a static block; for example:
private static final FileInputStream input;
static {
FileInputStream temp = null;
try {
temp = new FileInputStream("foo.txt");
} catch (FileNotFoundException ex) {
// log the error rather than squashing it
}
input = temp; // Note that we need a single point of assignment to 'input'
}
(There are better ways to handle the above scenario in practical code, but that's not the point of this example.)
Edge case: static blocks
As noted above, you can catch exceptions in static blocks. But what we didn't mention is that you must catch checked exceptions within the block. There is no enclosing context for a static block where checked exceptions could be caught.
Edge case: lambdas
A lambda expression (typically) should not throw an unchecked exception. This is not a restriction on lambdas per se. Rather it is a consequence of the function interface that is used for the argument where you are supplying the argument. Unless the function declares a checked exception, the lambda cannot throw one. For example:
List<Path> paths = ...
try {
paths.forEach(p -> Files.delete(p));
} catch (IOException ex) {
// log it ...
}
Even though we appear to have caught IOException, the compiler will complain that:
there is an uncaught exception in the lambda, AND
the catch is catching an exception that is never thrown!
In fact, the exception needs to be caught in the lambda itself:
List<Path> paths = ...
paths.forEach(p -> {
try {
Files.delete(p);
} catch (IOException ex) {
// log it ...
}
}
);
(The astute reader will notice that the two versions behave differently in the case that a delete throws an exception ...)
More Information
The Oracle Java Tutorial:
The catch or specify requirement
... also covers checked vs unchecked exceptions.
Catching and handling exceptions
Specifying the exceptions thrown by a method
So quoting from this page, which is titled: Exception-Handling Antipatterns Blog and seems to be written (or at least to be approved) by Oracle..
An unchecked exception probably shouldn't be retried, and the correct response is usually to do nothing, and let it bubble up out of your method and through the execution stack. This is why it doesn't need to be declared in a throws clause. Eventually, at a high level of execution, the exception should probably be logged.
I am not sure if I understand this. How can I log an unchecked exception? If I have something like:
public static void main(String args) {
foo();
// How do I know what to log here? The method I am calling
// is not throwing an Exception.
// Do I just blindly catch(Exception ex)?
}
static void foo() {
bar();
}
static void bar() {
baz();
}
static void baz() {
// I will do nothing as Oracle suggests and let this exception bubble up.. I wonder who is going to catch it and how this is going to be logged though!
throw new NullPointerException();
}
Can you help me understand what Oracle is suggesting here? I do not see any direct (or clear) way to catch runtime exceptions (I do not understand why it is not just called unchecked exceptions..) in higher levels and I am not sure how this suggested practice is useful. To me it would make more sense if it were talking about checked exceptions. Something like..
If a checked exception is thrown in a method that is not reasonable to be re-tried, the correct response is to let it bubble up and log..
You can also register a global ExceptionHandler that will handle the Exceptions that were not caught by your code:
Thread.setDefaultUncaughtExceptionHandler
This exception handle could then log whatever occured.
First of all, this is a general advice and it depends on the context. The idea behind it is that when a runtime exception occurs (ex. NullPointerException), the system is usually in an indeterministic state, meaning the rest of the code is not be guaranteed to execute as expected, so it's better to stop everything.
In most cases, your code will run in a separate thread and the exception will only stop the current thread, while the rest of the program keeps running.
This is not the case in your example, because everything is executed in a single thread, so the uncaught exception will effectively stop the whole program. In this scenario you might want to catch the exception and handle it.
public static void main(String args) {
try {
foo();
catch(Throwable t) {
t.printStackTrace(); // log exception
// handle the failure
}
}
You can also catch the exception earlier on, log and rethrow it further.
static void bar() {
try {
baz();
catch (Throwable t) { // catch
t.printStackTrace(); // log
throw t; // rethrow further
}
}
Edit: catch Throwable instead of Exception, will also catch Error
Note: Catching throwable is usually a bad idea, and should only be done with a specific purpose, not in general case. See #RC.'s comment.
As I understand it the documentation is suggesting that you have a generic handler at a high level of your code that logs such 'unexpected' (unrecoverable?) exceptions just as the comments in your main method suggest. So it might look something like this
public static void main(String args) {
try {
foo();
}
catch (ArithmeticException aex) { //if it's arithmetic log differently
log("arith issue! "+aex.getMessage());
}
catch (Exception ex) { //Otherwise do the best we can
log("unknown issue! "+ex.getMessage())
}
}
So there is still no path to recovery but at least before the process ends you get a chance to log the issue. You can also use the methods of Exception (or throwable) to get the stack trace and first causal exceptions in many case - so there is is a lot of extra useful information that might be logged.
There is a very straightforward way to catch unchecked exceptions, since they are all subclasses of RuntimeException or Error:
public static void main(String[] args) {
try {
// your code
} catch (RuntimeException | Error e) {
// handle uncaught exceptions, e.g.
e.printStackTrace();
}
}
How do I know what to log here? The method I am calling is not throwing an Exception.
As Joshua Bloch recommends in the Effective Java
Use the Javadoc #throws tag to document each unchecked exception that
a method can throw, but do not use the throws keyword to include
unchecked exceptions in the method declaration
And if you are using method wrapping in multilayered app i can recommend use exception translation:
Higher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction
See Effective Java item 61
So i think for your example actually you should use something like:
try {
bar();
} catch(NullPointerException e) {
throw new HigherLevelException(...);
}
The most important guideline regarding exceptions is that a method that couldn't sucessfully complete its task should throw an exception.
Only if you can guarantee successful completion of your method's task, you should catch an exception inside your method (without re-throwing this or another exception). From my experience that's only true in very specific situations, e.g. if you have an alternative way to try if some first attempt fails, or if you really really understand all possible causes of this specific Exception class that you are about to catch.
Speaking about RuntimeExceptions, there are so many different types of RuntimeException that you can hardly justify an assertion like "When such an exception arises in my code or a method called from inside my code, that won't affect the outcome of my method - I can continue just as if nothing happened." So, you should signal to your caller that you failed to fulfill your task, and the clearest way to do that is to let the exception ripple through, without try/catch block or throws declaration, just relying on Java's default behaviour.
In my opinion, the same reasoning applies to nearly all kinds of exceptions, not only RuntimeExceptions.
The difference with checked exceptions is that you have to declare them in the throws clause of your method. Then you have two choices: list the exception in the throws clause of your method (and all parent methods as well!) or catch the exception, wrap it in a new RuntimeException(ex), and throw that from your method.
With e.g. a typical GUI application, your users will be grateful if a problem in one menu function won't crash the whole application - probably other menu items might still work as expected. So, top-level commands or menu items are typically the places where to catch exceptions, tell the user something like "Oops!", log the exception to some file for later inspection, and allow the user to continue with another action.
In your main/foo/bar/baz application, I don't see a place where continuing after an exception makes sense. So the whole program should be aborted (which happens automatically in your case). If you want some error logging to a file, then establish an uncaught exception handler or wrap the body of main() in a try / catch(Throwable t) block. You'll probably want every exception logged, whatever type it is, so catch them all, and that's why I'm suggesting Throwable.
public static void main(String[] args) {
try {
foo();
}
catch(NullPointerException e){
System.out.println("NullPointerException in main.");
}
}
static void foo() {
bar();
}
static void bar() {
baz();
}
static void baz() {
// I will do nothing as Oracle suggests and let this exception bubble up.. I wonder who is going to catch it and how this is going to be logged though!
throw new NullPointerException();
}
OUTPUT :
NullPointerException in main.
Basically the error is expected at a higher level, so there is no need to catch it on the baz() method level. If I understood correctly.
You can catch them just like any other exception with try-catch block. But the benefit is that you don't have to.
Use cases can vary. To my mind, the most popular is when it doesn't make sense to catch the exception right in that place or the appropriate handling should be implemented several levels (in terms of methods) higher than the method, calling the one throwing the exception (sorry, if that is not clear enough).
For example, the typical web application layout in java is as follows: you have a layer of controllers, a layer of services and a layer of dao. First one is responsible for dispatching requests, the second one is for managing business logic and the last one makes actual calls to db. So here for example it often doesn't make much sense to catch the exception in service layer if something goes wrong on the dao level. Here unchecked exceptions can be used. You log an exception and throw an unchecked exception so it could be handled some levels above for a user to get valuable feedback of work of the application.
If in this case you throw a checked exception you will have to rethrow it every level above just to bubble up it to the place of the actual handling. So here the unchecked exception is better to use in order not to copy and paste all that ugly try-catch block, rethrowing an exception and add the throws clause to the method.
If the method is declared to throw the same exceptions thrown by some code and that code is also enclosed in a try/catch, will the exception be caught by the catch or will the error still be thrown? I am guessing that the catch has precedence although I am not 100% sure.
If I understand you correctly, you are asking:
void someMethod() throws SomeException {
try {
doSomethingElse()
} catch (SomeException e) {
// is this reached or does it throw from the method?
}
}
The catch clause will be triggered and the exception is considered handled. Unless you re-throw it from that block, it will not escape the method.
In my example, there is no need for your method to declare that it throws SomeException, because it doesn't.
Each catch block is an exception handler that handles the type of exception indicated by its argument. Once the exception is handled, it will not be thrown anymore unless you rethrow the exception in the catch block.
It is not a matter of one construct "taking precedence" over the other. They are saying different things.
(Borrowing #Duncan's example ...)
void someMethod() throws SomeException {
try {
doSomethingElse()
} catch (SomeException e) {
// is this reached or does it throw from the method?
}
}
Also, I will assume that SomeException is a checked exception.
This line here:
void someMethod() throws SomeException {
is saying that someMethod >>could<< throw SomeException. This is the contract: what the caller of the method needs to allow for.
It is not saying that it >>does<< throw the exception. What actually happens is determined by the behavior of the body of the method. In this example, the exception is being caught and handled, so we can say that even though the someMethod >>could<< throw the exception, in fact it >>does not<<.
OK ... but that is not the end of the story.
What if we changed the body of the method to not catch the exception? Now the ">>does not<<" becomes ">>could<<" ... depending on the signature for doSomethingElse() and its behavior.
What if we created a subclass that overrides someMethod with a different behavior. Now, the actual class of the target object will influence whether the exception can happen or not.
But through all of this, the meaning of throws SomeException in the method declaration remains the same. It tells the compiler that whenever this method is called, the caller must deal with the possibility of the checked exception ... even if there is no way that the code as currently written can propagate that exception.
To recap. Neither "takes precedence". They are saying different things.
I was wondering if there was a way to write a catch statement that is activated whenever any exception is thrown in a program. Thanks!
The problem with the answers you have received so far is that if you include a "catch-all" in your main, it will only catch exceptions thrown on the main thread.
A more robust way to catch all uncaught exceptions is to setup a DefaultUncaughtExceptionHandler for your project, for example, at the start of your main, you can call:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
//log the exception
}
});
Note that it is generally unreasonable to do anything but logging in there, as the Throwable could be anything, including unrecoverable errors.
You can make the type Exception. That will catch any Exception, but it also doesn't give the programmer much information on what went wrong. It's usually better to try to be more specific about the type of exception that has occurred, mainly for semantic reasons.
The theory
Every type of Java Exception extends the Exception type. Because Exception is a superclass of all exceptions, when an exception is thrown, regardless of it's type, it can still be implicitly casted to an object of type Exception.
Edit
As mentioned in the comments, there is also type Error that can be thrown, so to really catch everything using the Throwable type is best. Throwable is more general than Exception, but it still works on the exact same principle. It is the superclass of anything that can be thrown.
For Example
try{
// Some code
}
catch(Throwable e)
{
// Do something. Edited due to comment!
}
To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself)
From How can I catch all the exceptions that will be thrown through reading and writing a file?
try {
// exceptional block of code ...
// ...
} catch (Exception e){
// Deal with e as you please.
//e may be any type of exception at all.
}
The reason that works is because Exception is the base class for all runtime exceptions. Thus any runtime exception that may get thrown is an Exception.
The is because all runtime exceptions inherit from Exception. Note that there is a difference between an Error and Exception Unchecked exceptions in Java: Inherit from Error or RuntimeException?, In that case you may need to do:
try {
} catch(Throwable e) {
}
See this When should Throwable be used instead of new Exception?. One user notes:
Error is programmatically unrecoverable in any way and is usually not to be caught, except for logging purposes (which passes it through again). Exception is programmatically recoverable. Its subclass RuntimeException indicates a programming error and is usually not to be catched as well. See comments for additional information.
Yes, any error that falls through will be caught by this:
try {
//do things here
} catch (Exception e) {
//handle exception here
}
Note, however, that it's typically the wrong thing to do.
In your main, put all your code in
try {
//Your code
} catch(Exception e) {
//Handle exceptions
}
This will handle any exception invoked by your code.
I was not able to find any advice on catch blocks in Java that involve some cleanup operations which themselves could throw exceptions.
The classic example is that of stream.close() which we usually call in the finally clause and if that throws an exception, we either ignore it by calling it in a try-catch block or declare it to be rethrown.
But in general, how do I handle cases like:
public void doIt() throws ApiException { //ApiException is my "higher level" exception
try {
doLower();
} catch(Exception le) {
doCleanup(); //this throws exception too which I can't communicate to caller
throw new ApiException(le);
}
}
I could do:
catch(Exception le) {
try {
doCleanup();
} catch(Exception le1) {
//ignore?
//log?
}
throw new ApiException(le); //I must throw le
}
But that means I will have to do some log analysis to understand why cleanup failed.
If I did:
catch(Exception le) {
try {
doCleanup();
} catch(Exception le1) {
throw new ApiException(le1);
}
It results in losing the le that got me here in the catch block in the fist place.
What are some of the idioms people use here?
Declare the lower level exceptions in throws clause?
Ignore the exceptions during cleanup operation?
First, decide if you actually need to throw from the finally block - think carefully on that - in the case of a failed close() call... well, logging it is fine - but what can a higher layer of your API really do about the problem? So for 99% of the cases, you will log the secondary then re-throw the primary.
Next, if you do need to throw the secondary, decide if the various causes of the secondary exception are important. It will be rare that they are. So set the cause of the secondary to be the primary (either using an appropriate constructor, or initCause() ).
Finally, if you've must throw the secondary, and retain the full stack trace of the secondary and the primary - then you are in to creating a custom Exception to handle the situation. It's ugly, because you will probably want to derive from different parent classes. If this does arise, I suggest creating a helper class that is capable of filling the stack trace of a target exception in such a way that it produces a meaningful trace based on both exceptions (Be sure to use indentation for the secondary so nested exceptions are easy to pull apart).
But mostly, I suggest that you use the log-and-rethrow-primary paradigm. Focus on fixing the primary, and the secondary issues generally take care of themselves (the classic example here is an IO exception that munges things up so badly that the call to close() can't succeed either).
Use a finally block. If you are worried about swallowing the stack trace do the following:
Exception ex = new Exception(le.stackTrace());