While trying to print the stack trace in my browser window, I fail. Following is the sample of the exception block.
try {
// Add Code Here
} catch(Exception exc) { exc.printStackTrace();}
I am using google app engine as my server. What could be the reason the stack trace is not printing ?
Because there is no Exception to catch:
try {
// Add Code Here
}
You will only print a stack trace an Exception is thrown within the try block like this:
try {
throw new RuntimeException();
}
The method in question is implemented like this:
public void printStackTrace() {
printStackTrace(System.err);
}
If your container/IDE/framework redirects the stream then you will not observe it at the expected location, see also System.setErr(...);. And of course, I expect you to have checked that your code really throws an Exception (if an Error then it will not be caught by your clause).
You will need to change the default error output stream. Since you are most probably coding a servlet , you could change to :
exc.printStackTrace(response.getWriter());
This will print the exception trace into the browser window.
Related
I am quite new to Java and stumbled upon an problem, I can't understand (I am using Eclipse Luna for developing and executing):
I call a method that might throw an error and surrounded it with a try-catch-block:
try {
transaction.execute();
} catch (ModbusIOException e) {
log.debug("Fehler bei Modbustransaction: ModbusIOException - " + e.getMessage());
e.printStackTrace();
} ... // more catches
The execute-method actually throws the ModbusIOException - but it is not caught in the catch-block. In the console I got the following output:
net.wimpi.modbus.ModbusIOException: Read failed
at net.wimpi.modbus.io.ModbusTCPTransport.readResponse(ModbusTCPTransport.java:180)
at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:193)
at de.vksys.modbusclient.ModbusClient.getPlantState(ModbusClient.java:121)
at de.vksys.modbusclient.ReconnectingModbusClient.main(ReconnectingModbusClient.java:36)
If I click at the line with getPlantState Eclipse marks the line in the try-block above. But why isn't it caught there? I also checked the full name of the ModbusIOException in the catch block and is the same ... net.wimpi.modbus.ModbusIOException.
Any idea, what might be the reason? If you need more code to track this down, just tell me.
Thanks in advance,
Frank
It indeed caught the exception. You just printed the stack trace and that's what you see in the standard output.
Catching an exception, doesn't mean that it wont maintain the stack trace and handling exception means that you need to code it so you could recover from the exception (which is what has happened in your case else your program would have went to the parent method which called your method rolling back the stack i.e. in readResponse method) where you might say ok things happen or you rethrow the exception. for e.g. given a code as below:
void myMethod() {
try {
methodThatThrowsIOException();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("I will be printed");
If you didn't caught the exception, then you would never have executed print statement like "I will be printed"
}
I've come across some really strange behaviour in my Java code. There is a exception shown on my Eclipse log console saying Exception:java.lang.NullPointerException with no reference to the code where it occurred.
On debugging I found out a line where this occurred and so put it in try-catch hoping I catch it. However it didn't return in catch block.
The strange part being even though there's exception thrown at the line immediately after it executes and the execution continues normally.
Can some one please tell me the probable cause?
I could have attached the source code but I have checked the parameters and all seem fine.
My main reason for this post is to learn about such behavior if any of you coders ever came across.
Probably a problem with Eclipse. I have seen that behaviour before, and restarting Eclipse solved the problem.
Please check whether your builder is activated and the changed source code is build automatically. Otherwise your code changes will never get it into your runtime application.
I am pretty sure, that the executed source code is different to the source code shown in your editor.
If you see the exception's message but no stack trace, that is caused by code that looks like this:
try
{
// something which causes the exception
}
catch (final Exception err)
{
System.out.println(err);
}
The problem with this code is that it only prints the result of the exception's .toString() method. For most exceptions this is just the exception class and the message. This code omits the stack trace, thus making it much harder to debug the problem.
If the exception is to be caught, then change the code to look like this for the stack trace to be included in the output:
try
{
// something which causes the exception
}
catch (final Exception err)
{
err.printStackTrace();
}
I was trying to understand why to use exceptions.
Suppose if I have an program,
(without using try/catch)
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
System.out.println(str.length());
}
I got exception
Exception in thread "main" java.lang.NullPointerException
at com.Hello.ExceptionExample.ExceptionExample.main(ExceptionExample.java:22)
Now using try/catch,
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
try {
System.out.println(str.length());
} catch(NullPointerException npe) {
npe.printStackTrace();
}
}
}
I got Exception,
java.lang.NullPointerException
at com.Hello.ExceptionExample.ExceptionExample.main(ExceptionExample.java:9)
Now my question is,
In both the cases I have got the same message printed. So what is the use of using try/catch? and
What can we do after catching exception, in this case I have printed the stack trace. Is catch used only for printing the trace or for finding exception details using getMessage() or getClass()?
The difference is pretty big, actually.
Take the first one and add a line after the print:
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
System.out.println(str.length());
System.out.println("Does this execute?");
}
}
You'll see that Does this execute? isn't printed because the exception interrupts the flow of the code and stops it when it isn't caught.
On the other hand:
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
try {
System.out.println(str.length());
} catch(NullPointerException npe) {
npe.printStackTrace();
}
System.out.println("Does this execute?");
}
}
Will print both the stack trace and Does this execute?. That's because catching the exception is like saying, "We'll handle this here and continue executing."
One other remark, the catch block is where error recovery should happen, so if an error occurs but we can recover from it, we put the recovery code there.
Edit:
Here's an example of some error recovery. Let's say we have a non-existent file at C:\nonexistentfile.txt. We want to try and open it, and if we can't find it, show the user a message saying it's missing. This could be done by catching the FileNotFoundException produced here:
// Here, we declare "throws IOException" to say someone else needs to handle it
// In this particular case, IOException will only be thrown if an error occurs while reading the file
public static void printFileToConsole() throws IOException {
File nonExistent = new File("C:/nonexistentfile.txt");
Scanner scanner = null;
try {
Scanner scanner = new Scanner(nonExistent);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException ex) {
// The file wasn't found, show the user a message
// Note use of "err" instead of "out", this is the error output
System.err.println("File not found: " + nonExistent);
// Here, we could recover by creating the file, for example
} finally {
if (scanner != null) {
scanner.close();
}
}
}
So there's a few things to note here:
We catch the FileNotFoundException and use a custom error message instead of printing the stack trace. Our error message is cleaner and more user-friendly than printing a stack trace. In GUI applications, the console may not even be visible to the user, so this may be code to show an error dialog to the user instead. Just because the file didn't exist doesn't mean we have to stop executing our code.
We declare throws IOException in the method signature instead of catching it alongside the FileNotFoundException. In this particular case, the IOException will be thrown here if we fail to read the file even though it exists. For this method, we're saying that handling errors we encounter while reading the file isn't our responsibility. This is an example of how you can declare an irrecoverable error (by irrecoverable, I mean irrecoverable here, it may be recoverable somewhere further up, such as in the method that called printFileToConsole).
I accidentally introduced the finally block here, so I'll explain what it does. It guarantees that if the Scanner was opened and an error occurs while we're reading the file, the Scanner will be closed. This is important for many reasons, most notably that if you don't close it, Java will still have the lock on the file, and so you can't open the file again without exiting the application.
There are two cases when you should throw an exception:
When you detect an error caused by incorrect use of your class (i.e. a programming error) throw an instance of unchecked exception, i.e. a subclass of RuntimeException
When you detect an error that is caused by something other than a programming error (invalid data, missing network connectivity, and so on) throw an instance of Exception that does not subclass RuntimeException
You should catch exceptions of the second kind, and not of the first kind. Moreover, you should catch exceptions if your program has a course of action to correct the exceptional situation; for example, if you detect a loss of connectivity, your program could offer the user to re-connect to the network and retry the operation. In situations when your code cannot adequately deal with the exception, let it propagate to a layer that could deal with it.
try/catch will prevent your application from crashing or to be precise- the execution will not stop if an unintentional condition is met. You can wrap your "risky" code in try block and in catch block you can handle that exception. By handling, it means that do something about that condition and move on with execution.
Without try/catch the execution stopped at the error-making-line and any code after that will not be executed.
In your case, you could have printed "This was not what I expected, whatever, lets move on!"
Let's say you are connected to database but while reading the records, it throws some exception. Now in this particular case, you can close the connection in Finally block. You just avoided memory leak here.
What I meant to say is , you can perform your task even if exception is thrown by catching and handling it.
In the example you've given, you're right, there is no benefit.
You should only catch an exception if either
You can do something about it (report, add information, fix the situation), or
You have to, because a checked exception forces you to
Usual "handling" of an exception is logging the situation to a log file of your choosing, adding any relevant context-sesitive information, and letting the flow go on. Adding contextual information benefits greatly in resolving the issue. So, in your example, you could have done
public static void main(String[] args) {
try {
System.out.println(str.length());
} catch(NullPointerException npe) {
System.err.println(
"Tried looking up str.length from internal str variable,"
+" but we got an exception with message: "
+ npe.getMessage());
npe.printStackTrace(System.err);
}
}
when looking a message like that, someone will know based on the message what went wrong and maybe even what might be done to fix it.
If you are using Exception, don't
catch(NullPointerException npe) {
npe.printStackTrace();
}
simply
catch(NullPointerException npe) {
//error handling code
}
You are menat to remove error printing. And anyways catch general exception not just specific ones.
If you look at the two exceptions, they are actually different. The first one is referring to line 22, while the second one is referring to line 9. It sounds like adding the try/catch caught the first exception, but another line of code also threw an exception.
Consequently, the exception is being thrown because you never created a new String, or set a value to the string, unless it was done in a part of the code that is not shown.
Adding a try/catch block can be very helpful with objects that you have little to no control over, so if these objects are other than expected (such as null), you can handle the issue properly.
A string is normally something that you would instantiate first, so you shouldn't normally have to worry about using a try/catch.
Hope this helps.
To answer your original question Che, "when to use an exception?"
In Java - I'm sure you've already found out... There are certain methods in Java that REQUIRE the try / catch. These methods "throw" exceptions, and are meant to. There is no way around it.
For example,
FileUtils.readFileToString(new File("myfile.txt"));
won't let you compile until you add the try/catch.
On the other hand, exceptions are very useful because of what you can get from them.
Take Java Reflection for example...
try { Class.forName("MyClass").getConstructor().newInstance(); }
catch ( ClassNotFoundException x ) { // oh it doesnt exist.. do something else with it.
So to answer your question fully -
Use Try/Catch sparingly, as it's typically "frowned on" to EXPECT errors in your application.. on the contrary, use them when your methods require them.
Probably a newbie question, but everyone seems to use e.printStackTrace(), but I have always used System.out.println(e) when exception handling. What is the difference and why is e.printStackTrace() preferable?
The output stream used is not the same as pointed out by #Brian, but the level of detail is not the same either - you can try with the simple test below. Output:
With println: you only know what exception has been thrown
java.lang.UnsupportedOperationException: Not yet implemented
With printStackTrace: you also know what caused it (line numbers + call stack)
java.lang.UnsupportedOperationException: Not yet implemented
at javaapplication27.Test1.test(Test1.java:27)
at javaapplication27.Test1.main(Test1.java:19)
public static void main(String[] args){
try {
test();
} catch (UnsupportedOperationException e) {
System.out.println(e);
e.printStackTrace();
}
}
private static void test() {
throw new UnsupportedOperationException("Not yet implemented");
}
If you use System.out.println, then you're dumping your errors to the stdout, not stderr.
It's traditional to dump errors to standard error, so you can filter normal successful output from the error output. It's a common practise for command-line utilities and consequently a good idea to follow.
e.g.
myCommand 2> /tmp/errors > /tmp/results
will write errors to one log, and the results to another. Depending on your shell/invoking process etc. you can combine this info, throw errors away, react if any errors are thrown etc. See here for more info.
Using printStackTrace() is a good idea since you're dumping out where the exception took place. This is often invaluable for tracking errors that are unexpected since it'll give you a direct (if verbose) pointer to where exactly you ran into an error.
System.out.println(e) is equivalent to System.out.println(e.toString()): System.out is a PrintStream, PrintStream.println(Object o) calls PrintStream.println(o.toString()).
e.toString() returns the name of the class, and the exception's getLocalizedMessage().
e.printStackTrace() writes that information to System.err (not System.out) and also a stack trace, that is, the chain of methods that led to the exception. This is useful information.
I've often thought it would be nice if there was a method that returns a String containing the info that's output by e.printStackTrace(). Since there isn't you have to use e.getStackTrace() and write your own routine to output the resulting array of StackTraceElements.
Since the output of e.printStackTrace(); is System.err and usually I output my app log to a file, I recommend you to use both System.err and System.out to output errors.
public static void log(Exception e) {
e.printStackTrace(); // This goes to System.err
e.printStackTrace(System.out);
}
This way you can see the errors in the log file (in case you have one) and in the console.
System.out.println(e) will not give you your stack trace, just the error message and exception type, as well as being printed to the standard output as opposed to error output.
Bellow Program show the difference details
System.out.println(e); :- only showing the exception.
e.g.java.lang.ArithmeticException: / by zero
e.printStackTrace(); :- showing the details of exception and where
to cause exception in program with line number e.g.
java.lang.ArithmeticException: / by zero at
test.Test.main(Test.java:7)
package test;
public class Test {
public static void main(String args[]) {
try {
System.out.println(12 / 0);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
}
With System.out.println(e) you only get on to know what exception is thrown but with e.printStackTrace() you get information about what exception is thrown and what caused it.
The goal is to be able to do:
throw new RuntimeException();
without it printing:
Exception in thread "main" java.util.RuntimeException
at grame.GrameManager.add(GrameManager.java:40)
at grame.GrameManager.add(GrameManager.java:47)
at grame.Entity.<init>(Entity.java:56)
at grame.Entity.<init>(Entity.java:28)
at test.Test.main(Test.java:20)
(for example).
Is this possible? If so, how would I go about doing this?
Since exceptions are important, you could use a logging mechanism like log4j (http://logging.apache.org/log4j/1.2/) and set the logging to a different level when you don't want some exceptions to be printed or log to a file instead of console for example.
If you just don't care about the exception, catch it and do nothing with it (empty catch, which is awful).
You can redirect System.err by setting System.setErr(null);
No thrown exception ever directly generates a stacktrace to the error console. It's up to the code who is calling it to do so. In the case of a main program:
public static void main(String args[]) throws Exception {
// do something that throws an exception
}
If you don't catch the exception, the system will actually spit it out to the console i believe.
Somewhere along the way, you need to deal with the exception. If showing it in the GUI is what you want, then you'll have to do something like this:
public interface ExceptionHandler {
void handleException(Exception e);
}
public static void main(String args[]) {
ExceptionHandler exceptionHandler = ...;
try {
// something that might throw an exception
}
catch (Exception e) {
exceptionHandler.handle(e);
}
}
Just catch the exception, and don't put anything in the catch block.
I should add that doing this is generally a bad idea. Having that stack trace, or some sort of message is very useful when finding out what went wrong in your program.
If you want the method to kill the program without printing a stack trace, place it in a try/catch block, and under catch simply use the statement:
System.exit(1)
This lets the system know that the program exited with an irregular (non-zero) state, but does not print anything to System.err.
All that you really need to do is catch it... However, this is a really bad idea. You may want to make your own exception and catch that. This way you will not swallow exceptions that you should not be ignoring. The only time that you should really consider to do this, is if you cannot allow your application to blow up. If that is the case then you should at the very least log the error.
This explains it better than I can (and is a good resource regardless). Basically, it suggests that:
"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".
Like this:
try {
some code...
} catch (RuntimeException e) {
}
1. Java compiler only cares during compilation that you have given a catch for a try, whether you implement any code in the catch or not.
2. You can keep the catch block empty, or print it on the console, log it..etc....
eg:
try{
}catch(Exception ex){
}
3. But printStackTrace() prints the method name, class name , file name and the line number where the exception has occurred.