Anyone know why Exception().getMessage return to 1? What does it mean? I have tried to find the answer but nothing found, thank.
Use e.printStackTrace instead of e.getMessage() in case of exception. It will display all the information required to debug the issue, whereas printing only the message of the exception doesn't tell you almost anything.
If using a logger, use the form that accepts an exception/throwable, usually of the form logger.error("Custom error message", e);, and the stacktrace will be printed.
Related
In regards to Log4j v2, I'd like to call log.error(exceptionTypeObj) and have the stack trace printed to my logfile instead of exceptionTypeObj.toString(). Is that possible?
I'd rather write code like log.error(e) and be done with it.
It's error prone and redundant for me to keep writing something like log.error("error", exceptionTypeObj).
The String parameter is redundant because you are not using it for the correct purpose. An Exception will tell you what error occurred but it won't tell you what you were trying to do when it happened. That is why you should always provide the string. Provide a String that says something like "Error occurred while attempting to update the user profile for user {}", and then provide the user name or id.
Without the String parameter you are forcing your support staff to call engineering to find out what the exception means and what they should do about it.
I tried to execute jar from Java code with:
Runtime.getRuntime.exec("java -jar a.jar")
I could get InputStream with error from Process.getErrorStream().
Can I take this stream and if it has an Exception transform it to Exception and throw in my upper application?
Has Java some mechanism to convert string to Exception?
EDIT: Or maybe java has some mechanism like System.exit(int code) but with Exception? So in parent app I can do something like process.waitFor() but take an exception instead int code?
Process.getErrorStream() returns an IntputStream connected to the error output of the subprocess.
So, it is not exception in Java terms. It's an output information which must be considered as an error detected by the process during its execution.
Java don't convert automatically InputStream or String to Exception.
So, you could read this stream in a String and throw a custom exception with as message the string.
If you want that the caller may be able to handle this exception in a clean way, don't use a RuntimeException but a checked exception :
public class ProcessExecutionException extends Exception{
public ProcessExecutionException(String errorOutputMsg){
super(errorOutputMsg);
}
}
Edit for answering your comment :
Yeah, but how to check is inputstream line is a part of stacktrace of
child exception
it's not a stracktrace but error messages as explained.
and how much line from IS i should add to ProcessExecutionException?`
You have to read all the errorStream until it returns null if you want to capture all error output.
In my case my jar is a Spring Application and it write to error stream
nor only Exception that i really need to catch, also some information
like "Error, you have no sl4j xml file, etc - like example". And i
need only really important exception
How the classes producing errors in output may guess if it is important for you or not ?
You must decide yourself which error message pattern should be considered as an important error or not.
Personally, if when my process is run, I have a not well configured logger, I will kill it and correct this problem before starting it again.
If you have input in the ErroStream, you can also inspect the value of the Process.exitCode() (0: normal termination, else problem).
If it is different from 0, you can suspect that it not only a little problem.
Here, some tracks to try.
Can i return something to exit like in System.exit()
In the child process, you can try to intercept all exceptions not handled which may be triggered . You can do it whatever the way (aspect, global try/catch, filter...) .
In this way, if you intercept an exception not handled and that you consider that the application must be terminated, you can do a System.exit with the expected code by the parent process.
In this way, in the parent, if Process.exitCode() matchs with expected code for important exception, you can handle it as you wish.
My question is: it better to log with getMessage or with toString or both? taking in to account errors thrown by open source. Saw the questions in the comments but did not get an answer to this. Maybe I missed something ? Do not mind the small performance hit of logging one of them, but do not want to log both unless there is a good reason.
Meaning log(ex) or log(ex.getMessage), Not talking about stack trace.
Saw 1 , 2 and 3
Logging exceptions : which is better:
log.warn(ex.getMessage(), ex) or log.warn(ex, ex);
I noticed sometimes getMessage returns empty or null, so in general practice is there any reason not to use :
log.warn(ex, ex);
As it seems to print the class name and the message (if set) ? I guess one reason could be if a sub class has over ridden to string not to print the message, but in reality do any of the hibernate, apache or spring libs do that?
How about
log.warn("some descriptive message, maybe with context {}",
someId, ex);
The exception details will already be printed as part of the stacktrace, so you don't need to include them in the message usually.
In case you want to suppress the stacktrace and only print the exception message, usually, ex.toString() works better than ex.getMessage(), because it also includes the exception class name, which the message does not. In fact, often the message is empty (for example with NullPointerExceptions).
I got NullPointerException error after using toString().substring() . I need to use this method. Help me please. I am not very sure i can use that method inside the query.
Orginal
String selectItemMasDetl="select MMITNO,MMITDS,MMALUN,MMSPUN from"+DBConnect.SCHEMA+".mitmas where MMCONO=888 and MMITNO="+ItemNo+"'";
Use ToString().substring()
String selectItemMasDetl="select MMITNO,MMITDS,MMALUN,MMSPUN from"+DBConnect.SCHEMA+".mitmas where MMCONO=888 and MMITNO="+ItemNo.toString().substring(0,4)+"'";
error log
java.lang.NullPointerException
[12/13/11 16:24:28:594 SGT] a6cc007 SystemErr R at com.------erp.report.stocklotsalesreport.StockLotSalesReportGet.getItemMasDetl
ANS:
selectItmMas="select MMITNO,MMITDS,MMALUN,MMSPUN from "+DBConnect.SCHEMA+".mitmas where MMCONO=888 and MMITNO like '"+ salesRecordListTO.getItemNo().trim() +"%'";
I use like operator and pass parameter instead of using trim. Now i get the result i want.
Thank you so much guys.
It means that at least in some cases either ItemNo or, DBConnect or the returned value of the toString() (as suggested) is null. The problem is that you don't have a stack trace, and so you can't be sure where the error is thrown. It could be even on another line, for what we (don't) know now.
Try to wrap with a try catch the relevant lines and print a stack trace, check the line of code where is happening, and post here again. Here is how:
try {
//code throwing exception
} catch (Exception ex) {
ex.printStackTrace();
}
Side note: seems that you need a space after the from, also you're closing a single quote, but I don't see the opening. Below, for reference, your code, only reformatted, not fixed:
String selectItemMasDetl = "select MMITNO,MMITDS,MMALUN,MMSPUN from"
+ DBConnect.SCHEMA + ".mitmas where MMCONO=888 and MMITNO="
+ ItemNo.toString().substring(0,4) + "'";
NullPointerExeption means that ItemNo is null, so when trying to use ItemNo.toString(), it will be interpreted as null.toString() which will throw the exception.
A check on null is one possibility (the easiest), see answer of Stivlo.
Depending on how quick the query is a count query can be done also, if count ==0 don't bother to do the real query.
Oops, sorry, not reading good: the null exception is already in building the query string. Well maybe this is of use in your next nullpointer exception :)
StringBuilder might be a solution, but than I think you'll get an invalid querystring, just use Stivlo's answer.
This is probably a newbie question, but hope you can help me. :) I have something like this:
try
{
//try to do something there
}
catch (IOException e)
{
//handle the exception
e.printStackTrace();
}
I am using NetBeans IDE and for some reason the printStackTrace is underlined in a squiggly line. When I press Alt+Enter, it says Throwable.printStackTrace() should be removed. What does this mean? Could anyone give more insight as what this may mean? Or can I ignore this?
Thanks!
Try:
e.printStackTrace(System.out);
It is just a recommendation. In eclipse it is fine - I believe it is just the IDE telling you that there are more conventional methods of doing it, like some of the other answers.
I find that it is useful for debugging, and that you should tell users when a fatal error is going to occur, to use a debug mode (like a console switch -d) to collect these logs.
It's probably because printStackTrace() doesn't really handle the error as much as it just dumps the stack in the console. It acts as a placeholder until you replace it with proper error handling (if it is needed at all) and replace the output with a logger of some sort.
e.printStackTrace();
Is not good practice because it prints in the default ErrorStream, which most of the times is the console!
NetBeans should be warning you about that. The good practice about it, is logging the message. Follow same reference:
http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html
EDIT
See first comment bellow to more info.
Just printing a stack trace is not enough. Printing the exception's stack trace in itself doesn't mean that it is completely bad practice, but printing only the stack trace when an exception occurs is an issue.
Always log exceptions(using a good logging framework), but do not expose them to the end-user. And keep ensure that showing stack traces only in development mode.
I myself use(most of the time) logger.log(Level.SEVERE, <exception>.getMessage(), <exception>);.
when netbeans suggest you to handle the exception 'Surround Statement with try-catch', if you click on this, it will generate):
try {
//something need to be handle(exception that throw)
} catch (SQLException ex) {
Logger.getLogger(ClassName.class.getName()).log(Level.SEVERE, null, ex);
}
Which is better than ex.printStackTrace();.
These may help:
Best Practices for Exception Handling
Javarevisited- logging's.
What are the latest options in Java logging frameworks?
Benchmarking Java logging frameworks.