I have a java class which is throwing IOException.I have some code in Catch block which i need to debug. I don't know in which case my java class is throwing exception. So I need to go to catch block explicitly without throwing. Can it be possible.
Please help me out.
Code in a catch block is not executed if no matching exception is thrown in the try block.
The only way to execute it is to cause the IOException to be thrown.
You can just put an explicit throw new IOException(); as the last line in the try block.
Alternatively, you might be able to pull the contents of the catch block into a separate method, which you can then invoke explicitly.
Control wont goto catch block if exception is not thrown. Put the code in finally block which you want to execute irrespective of whether exception thrown or not.
Sample:
try {
} catch() {
} finally {
//Put code here
}
but if the exception is thrown you will be directed towards finally block or you can post sample code so one might help you
Related
In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block.
Is there a more elegant way of doing this? Perhaps an API call that will reveal this?
Here's some rough code of what I'm talking about:
Throwable t = null;
try {
stream.write(buffer);
} catch(IOException e) {
t = e; //Need to save this exception for finally
throw e;
} finally {
try {
stream.close(); //may throw exception
} catch(IOException e) {
//Is there something better than saving the exception from the exception block?
if(t!=null) {
//propagate the read exception as the "cause"--not great, but you see what I mean.
throw new IOException("Could not close in finally block: " + e.getMessage(),t);
} else {
throw e; //just pass it up
}
}//end close
}
Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant.
Maybe something like Thread.getPendingException() or something similar? For that matter, is there an elegant solution in other languages?
This question actually spawned from comments in another question that raised an interesting question.
Your idea about setting a variable outside the scope of the try/catch/finally is correct.
There cannot be more than one exception propagating at once.
Instead of using a Boolean flag, I would store a reference to the Exception object.
That way, you not only have a way to check whether an exception occurred (the object will be null if no exception occurred), but you'll also have access to the exception object itself in your finally block if an exception did occur. You just have to remember to set the error object in all your catch blocks (iff rethrowing the error).
I think this is a missing C# language feature that should be added. The finally block should support a reference to the base Exception class similar to how the catch block supports it, so that a reference to the propagating exception is available to the finally block. This would be an easy task for the compiler, saving us the work of manually creating a local Exception variable and remembering to manually set its value before re-throwing an error, as well as preventing us from making the mistake of setting the Exception variable when not re-throwing an error (remember, it's only the uncaught exceptions we want to make visible to the finally block).
finally (Exception main_exception)
{
try
{
//cleanup that may throw an error (absolutely unpredictably)
}
catch (Exception err)
{
//Instead of throwing another error,
//just add data to main exception mentioning that an error occurred in the finally block!
main_exception.Data.Add( "finally_error", err );
//main exception propagates from finally block normally, with additional data
}
}
As demonstrated above... the reason that I'd like the exception available in the finally block, is that if my finally block did catch an exception of its own, then instead of overwriting the main exception by throwing a new error (bad) or just ignoring the error (also bad), it could add the error as additional data to the original error.
You could always set a boolean flag in your catch(es). I don't know of any "slick" way to do it, but then I'm more of a .Net guy.
Use logging...
try {
stream.write(buffer);
} catch(IOException ex) {
if (LOG.isErrorEnabled()) { // You can use log level whatever you want
LOG.error("Something wrong: " + ex.getMessage(), ex);
}
throw ex;
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException ex) {
if (LOG.isWarnEnabled()) {
LOG.warn("Could not close in finally block", ex);
}
}
}
}
In vb.net, it's possible to use a "Catch...When" statement to grab an exception to a local variable without having to actually catch it. This has a number of advantages. Among them:
If nothing is going to 'ultimately' catch the exception, an unhandled exception trap will be fired from the spot of the original exception. Much nicer than having the debugger trap at the last rethrow, especially since information that might be needed for debugging won't yet have gone out of scope or been swept up by 'finally' statements.
Although a rethrow won't clear the stack trace the way "Throw Ex" would, it will still often jinx the stack trace. If the exception isn't caught, the stack trace will be clean.
Because this feature is unsupported in vb, it may be helpful to write a vb wrapper to implement the code in C (e.g. given a MethodInvoker and an Action(Of Exception), perform the MethodInvoker within a "Try" and the Action in a "Finally".
One interesting quirk: it's possible for the Catch-When to see an exception which will end up getting overwritten by a Finally-clause exception. In some cases, this may be a good thing; in other cases it may be confusing. In any event, it's something to be aware of.
This question already has answers here:
When to catch the Exception vs When to throw the Exceptions?
(8 answers)
Closed 3 years ago.
So I have two general questions about java in general. The first is when would one use a try/catch in the body of the method versus using throws exception in declaring the method? Here is a little demonstration of what I mean. This:
public void whileChatting() throws IOException{}
versus
public void closeConnection() {
try {
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
And then my second question is when does one know what type of exception to either catch or throw? By that I mean exceptions such as IOException or EOFException and so on...
If there's a good link someone could send me teaching all this (being that it's probably more complicated than I think) I would be just as grateful as if you answered it.
Thanks.
Throwing Exceptions
In your first example,
public void whileChatting() throws IOException{}
means that it will just throw the exception to whatever is calling the function. It can then be caught while calling that method with a try-catch block. such as
try{
whileChatting();
}
catch(IOException e){
e.printStackTrace();
}
Throwing a method basically propagates it up the chain, and so any method that calls this method will need to also include throws IOException, or the exception will need to be dealt with in the higher level method (by means of a try-catch block usually).
Catching Exceptions
Catching an exception is a way to gracefully deal with exceptions. The common thing to do is e.printStackTrace(); which prints details of the error to the console, however it's not always necessary. Sometimes you may want to do a System.exit(0) or even a System.out.println("Error in method whileCalling()")
With a catch block you can catch any type of exception! you can also do a try-catch-finally block which will run the code in the try block, catch any exceptions, and whether or not any exceptions are caught it will enter the finally block and run that code.
To know what Exception you might need to catch, you can look at the Javadocs for the class that may throw the exception. There you will find a list of every possible thing that the class can throw. You can also just catch Exception which will catch any Exception imaginable! (Well, granted it extends Exception)
And finally you can link catch blocks together like so.
try{
whileCalling();
}
catch(IOException e){
//handle this situation
}
catch(FileNotFoundException e){
//handle this situation
}
catch(Exception e){
//handle this situation
}
This will work like and else-if block and not catch duplicates.
So to answer your questions basically:
1: To throw an Exception means to have somebody else deal with it, whether this be another class, another method, or just to hoping it doesn't happen or else your program will crash(pretty bad practice).
2: To use a try catch block is to actually deal with the Exception however you see fit! printing out the stacktrace for debugging or giving the user a new prompt to re-input something maybe. (For instance a prompt that the user needs to enter a file location and then it throws a FileNotFoundException)
Hope that helps!
Two good rules of thumb:
You should only catch exceptions that you can actually handle
Throw Early/Catch Late
There's no hard and fast answer.
In general, you'll probably use "throws" much more often than you'll have a custom "try/catch". Simply because you'll have relatively few "decision" modules that "know how to recover", but you'll have correspondingly "many" modules that could throw exceptions.
You use try/catch when you want to treat its reason, otherwise you should propagate it so it can be treated at the right time.
A good start would be javadoc and tutorialspoint for exceptions
Basically is something like this:
throws - the function that throws and exception tells it's parent function that somenthing it's wrong. For instance you have a createFunction() throws SQLException where you are trying to insert 100 item in a database but the creation of number 98 fails. The createFunction() is used in your main() who receives this SQLException;
try/catch - the main() knows that createFunction() is suppose to throw an SQLException if something goes wrong so when it implements it puts it in a try/catch block, this way if an SQLException is actually thrown you can execute a fall-back plan in the catch block such as a database rollback.
Actual code of what I just said:
createFunction(Connection connection) throws SQLException {
//insert items in the database
}
main(){
try{
createFunction(connection);
}
catch (SQLException e){
connection.rollback();
}
}
I am new to Java language and cannot understand the behavior of finally block in this program. This program should exit after printing BC whereas it is printing BCD. Please help.
class Main
{
public static void main(String [] args)
{
try
{
badMethod();
System.out.print("A");
}
catch (Exception ex)
{
System.out.print("B");
}
finally
{
System.out.print("C");
}
System.out.print("D");
}
public static void badMethod() throws Exception
{
throw new Exception(); /* Line 22 */
}
}
You're catching the exception (in the catch block) and not rethrowing it - so you're effectively handling the exception, and execution then proceeds as if it weren't thrown. The program only exits because it reaches the end of the main method - it's not like it's terminated abruptly.
If you change your code to either rethrow the exception from the catch block or just don't catch it in the first place (both of which will require you to declare that main throws Exception, of course) then it won't print D.
There is nothing to cause the program to exit.
The whole point of a catch block is to catch the exception and prevent it from propagating further.
After catching an exception, execution continues.
The finally block doesn't finalize the program, it just ensure to execute every time the try catch block runs whereas there is an exception or not..
It would print BC if you re-throw the exception in catch block.
catch (Exception ex)
{
System.out.print("B");
throw ex;
}
Then you'll have to declare your main as
public static void main(String [] args) throws Exception
Finally is called at the end of a try/catch block. It gets called even if the try fails and the catch is executed. The Finallyblock itself is only not executed if the program is killed somehow (JVM dies, forced to close, etc.)
In your example D is executing because it is outside of the try/catch/finally{} blocks.
There is a nice blog post on catching exceptions and the try/catch/finally behaviour here.
Which is correct. The above code will.
Try to execute badMethod and will fail
Execute the code in catch
Execute the code in finally
Continue in execution - print out the D
The finally block is processed after the try or catch block runs (depending on whether an exception was thrown/caught or not). If the exceptions were all caught properly and handles by the catch, it will run finally and then continue running the rest of the method.
Finally is the must executable block of java program.
It allows all the allocated resources of the currently running program to get free and make it available for the other applications if required.
This is mainly used when we share the common resources like Database or the devices.
Think of the finally block as an independent block of code(s) you'll still expect your method to continue executing irrespective of whether an exception occurs or not.
And so in your case, badMethod throws an exception which is consequently caught by the catch block, your main then continue by executing the finally block independently.
In other words, if badMethod decides not to throw an exception, your finally block would still continue execute before reaching the end of the method.
Therefore with finally been an independent block it is then possible to also do something like this in your main code if prefered.
try
{
fooA();
}
finally
{
fooB();
}
Your program is functioning in the following way:
1. Call a bad method that throws an exception
2. Catch the exception
3. Execute the finally block
4. Resume
In Java, when an exception gets thrown it does not necessarily end program execution if the exception is handled. Your program does not actually handle the exception but catches it anyway and this is enough for the JVM to think it's ok to resume execution.
The output BCD is quite the right output.
What does try do in java?
try is used for exception handling.
http://java.sun.com/docs/books/tutorial/essential/exceptions/try.html
The try/catch/finally construct allows you to specify code that will run in case an exception has occured inside of the try block (catch), and/or code that will run after the try block, even if an exception has occured (finally).
try{
// some code that could throw MyException;
}
catch (MyException e){
// this will be called when MyException has occured
}
catch (Exception e){
// this will be called if another exception has occured
// NOT for MyException, because that is already handled above
}
finally{
// this will always be called,
// if there has been an exception or not
// if there was an exception, it is called after the catch block
}
Finally blocks are important to release resources such as database connections or file handles no matter what. Without them, you would not have a reliable way to execute clean-up code in the presence of exceptions (or return, break, continue and so on out of the try block).
It allows you to attempt an operation, and in the event an Exception is thrown, you can handle it gracefully rather than it bubbling up and being exposed to the user in an ugly, and often unrecoverable, error:
try
{
int result = 10 / 0;
}
catch(ArithmeticException ae)
{
System.out.println("You can not divide by zero");
}
// operation continues here without crashing
try is often used alongside catch for code that could go wrong at runtime, an event know as throwing an exception. It is used to instruct the machine to try to run the code, and catch any exceptions that occur.
So, for example, if you were to request to open a file that didn't exist the language warns you that something has gone wrong (namely that it was passed some erroneous input), and allows you to account for it happening by enclosing it in a try..catch block.
File file = null;
try {
// Attempt to create a file "foo" in the current directory.
file = File("foo");
file.createNewFile();
} catch (IOException e) {
// Alert the user an error has occured but has been averted.
e.printStackTrace();
}
An optional finally clause can be used after a try..catch block to ensure certain clean-up (like closing a file) always takes place:
File file = null;
try {
// Attempt to create a file "foo" in the current directory.
file = File("foo");
file.createNewFile();
} catch (IOException e) {
// Alert the user an error has occured but has been averted.
e.printStackTrace();
} finally {
// Close the file object, so as to free system resourses.
file.close();
}
Exception handling
You're talking about a "try/catch" block. It's used to capture exceptions that may occur within the block of code inside the "try/catch". Exceptions will be handled in the "catch" statement.
It allows you to define an exception handler for a block of code. This code will be executed and if any "exception" (null pointer reference, I/O error, etc) occurs, the appropriate handler will be called, if one is defined.
For more information, see Exception Handling on wikipedia.
I am trying to call another JAR's main function. Now, this main function is enclosed under a try and catch block.
But when the main call returns a "NullPointerException" the program just crashes instead of catching it.
So, for example
try {
somelibary.main()
}
catch (Exception e) {
System.out.println("Exception Caught");
}
This code dosent catch NullPointerException from the main().
Does anyone know the reason y?
Your code, as shown, will definitely catch a NullPointerException thrown by somelibrary.main(). If the application stops anyway due to a NullPointerException there's a fair chance that somelibrary at some point catches the exception, dumps a stack trace and calls system.exit()
In that case the question is not how to catch a NPE, but how to prevent System.exit() from actually exitting.
And the answer to that question can, of course, be found on StackOverflow to, right here. Just install a SecurityManager before the call to someLibrary, and reset the securityManager afterwards.
It's possible that the other main function is doing its own error handling, à la
public static void main(String[] args) {
try {
....
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
If that's what the other main function is doing, then you won't be able to catch its exceptions. Do you have the code for this main function?
With the code you are showing, you will catch also the NullPointerException. But the execution will go on after the catch-block. So the execution of somelibary.main() is stopped in this case. If your main() is not contain more code, the program will end after catching the exception. That's what likely happens. You could post the complete code of your main, to verify this.
Addition: You want to know how to go on with the execution of the program. But in this case somelibrary.main() is stopped by throwing the exception. The only option in the main-class will be a loop, that reexecutes somelibrary.main(). The other possibility is to catch the Exception at some higher level (main input-loop) where you can ignore the problem and go on with the execution of the code. As you say you execute another jars-main I suspect you cannot change the code of the other jar. So you are only left with reexecute the other main:
boolean ended = false;
while (!ended)
{
try {
somelibary.main()
ended = true;
}
catch (Exception e) {
System.out.println("Exception Caught");
}
}
This code restarts the other main on an exception but ends if the other main ends normally.
Perhaps you could execute the main method in another process using Runtime.exec, then capture the result or the error from out/err stream.