I am coding a method that return an instance of FragmentManager as shown in the code belwo.
the prblem is, I want to throw an exception if the context passed to the method is null and then terminate the App.
what happens is, when I pass null to the method mentioned below, the App closes but the message in the NullPointerException which is :
getFragmentManagerInstance: Context reference is null
is not displayed
please let me know how to throw an exception and terminate the App correctly.
libs:
public static FragmentManager getFragmentManagerInstance(Activity activity) throws Exception {
try {
if (activity != null) {
return activity.getFragmentManager();
} else {
throw new NullPointerException("getFragmentManagerInstance: Context reference is null");
}
} catch (NullPointerException e) {
System.exit(1);
return null;
}
}
Just remove the try block. Simply typing
if (activity != null) {
return activity.getFragmentManager();
} else {
throw new NullPointerException("getFragmentManagerInstance: Context reference is null");
}
will do what you want, since NullPointerException is an unchecked exception.
The message "getFragmentManagerInstance: Context reference is null" is being stored in e. You need to print it to make it display on the screen.
In the catch block, add a print statement before System.exit(1)
catch (NullPointerException e) {
System.out.println(e);
System.exit(1);
return null;
}
is not displayed
Sure, that's because you're swallowing the exception:
} catch (NullPointerException e) {
System.exit(1);
return null;
}
The message is carried in e, and you're not using that in the catch block.
Note that it is almost never the right thing to do to catch a NullPointerException. In this case, you can simply print the message and terminate the app directly:
if (thing == null) {
System.err.println("It's null!");
System.exit(1);
}
Just use e.printStackTrace()
before System.exit(1)
and it will print as you wished
The message is not being displayed because you haven't written any code to print it. If you want to display message, add e.printStackTrace(); before exiting.
In order to print some information you need to provide them to an output stream such as System.out or System.err.
By default if you call ex.printstacktrace() it will print the exception within in System.err.
You can also use ex.printstacktrace(System.out) to choose where you send the information such as a file, the console or any output.
Also your application will immediately stop after the System.exit so your line of code need to be before the exit.
I'm suprised this hasn't been stated yet, change your catch block to
} catch(NullPointerException e){
System.err.print(e.getMessage());
System.exit(1);
return null;
}
And if you want to print a message to the user, consider using a Toast instead of Exception message.
Related
I have a program developed and it has a single entry point. A Try catch block is surrounding it.
try {
Runner runner = new Runner();
// Adhoc code
UIManager.setLookAndFeel(new NimbusLookAndFeel());
runner.setupVariables();
runner.setLookAndFeel();
runner.startSessionFactory();
runner.setupApplicationVariables();
runner.setupDirectories();
// This will be used to test out frames in development mode
if (Runner.isProduction == true) {
execute();
} else {
test();
}
} catch (Exception e) {
SwingHelper.showErrorMessageMainFrame(e.getMessage());
Logger.getRootLogger().error(e);
e.printStackTrace();
}
But suppose a null pointer exception is thrown, the message box is empty since the Exception doesn't contain a message. For this I added a logic-
if(e instanceof NullPointerException){
NullPointerException n =(NullPointerException) e;
SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at ");
}else{
SwingHelper.showErrorMessageMainFrame(e.getMessage());
}
This works all fine but I also want the line number to be displayed. How can I get it done. How can I get the line number of the exception?
Among the answer to this question, you can use this snippet:
public static int getLineNumber() {
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
Althought is recommended to use a logging library such as log4j.
The metadata for the exception is stored in StackTraceElement class, which you can get from your exception by calling getStackTrace().
Example of using it is:
if (e instanceof NullPointerException) {
NullPointerException n = (NullPointerException) e;
StackTraceElement stackTrace = n.getStackTrace()[0];
SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at " + stactTrace.getLineNumber());
}
if(e instanceof NullPointerException){
NullPointerException n =(NullPointerException) e;
SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at line" + e.getStackTrace()[0].getLineNumber());
} else {
SwingHelper.showErrorMessageMainFrame(e.getMessage());
}
Wow I was ninja'd by those above...
EDIT: Forgot to indent
I have this line of Code
try {
String txtText = article.getTxtText().toString();
if (StringUtils.hasText(article.getTxtText().toString())){
textPropertyList.add(txtText);
}
String txtLongText = article.getObjLongTextData().toString();
if (StringUtils.hasText(txtLongText)){
textPropertyList.add(txtLongText);
}
String txtShortText = article.getObjShortTeaserData().toString();
if (StringUtils.hasText(txtShortText)) {
textPropertyList.add(txtShortText);
}
} catch (NullPointerException e) {
}
It is possible, that only one of the three properties are set. But if one property isnt set, I get this NullpointerException. I catch it, but then the try-Block isnt continued.
So e.g. if the article.getTxtText() method returns null, I dont get the txtLongText and txtShortText Strings either, although at least one of them has a not empty String set.
So the question is, how can I continue the try-block although there's is an Exception caught?
Thanks a lot.
You should either use 3 try-catch blocks or just use a null-check around every case.
if (article.getTxtText() != null) {
// do part 1
}
if (article.getObjLongTextData() != null) {
// do part 2
}
I would imagine that the correct approach to this is to have three try/catch blocks around each point of code. The whole point of a try block is that you are trying the code as a lump and if it fails anywhere you abandon it. For what you are describing you would need three try/catches around each possible point of failure.
That having been said you are probably better off testing for null rather than relying on exception handling to do that. Exception handling should be for exceptionalm unforeseen events, not for flow control in a program.
If you must do this with exceptions (and I don't think you should), then you need to have 3 separate try/catch blocks:
try {
String txtText = article.getTxtText().toString();
if (StringUtils.hasText(article.getTxtText().toString())){
textPropertyList.add(txtText);
}
} catch (NullPointerException e) {}
try {
String txtLongText = article.getObjLongTextData().toString();
if (StringUtils.hasText(txtLongText)){
textPropertyList.add(txtLongText);
}
} catch (NullPointerException e) {}
try {
String txtShortText = article.getObjShortTeaserData().toString();
if (StringUtils.hasText(txtShortText)) {
textPropertyList.add(txtShortText);
}
} catch (NullPointerException e) {}
Once an exception is thrown in your code you cannot restart execution in the middle of the try block.
Having said that I would always prefer to detect the null pointer with an if test rather than relying on exception handling for this non-exceptional condition.
do defensive programming ,check for nulls.
if ( variable != null ){
...
}
The simplest and better approach from my point of view would be break the try - catch block in three different try-catch block, something like the following :
try {
String txtText = article.getTxtText().toString();
if (StringUtils.hasText(article.getTxtText().toString())){
textPropertyList.add(txtText);
}
} catch (NullPointerException e) {
//Handle Exception
}
try {
String txtLongText = article.getObjLongTextData().toString();
if (StringUtils.hasText(txtLongText)){
textPropertyList.add(txtLongText);
}
} catch (NullPointerException e) {
//Handle Exception
}
try {
String txtShortText = article.getObjShortTeaserData().toString();
if (StringUtils.hasText(txtShortText)) {
textPropertyList.add(txtShortText);
}
} catch (NullPointerException e) {
//Handle Exception
}
I'd recommend a different design:
private void addProperty(Object property, Collection<String> properties) {
if (property == null) {
return;
}
String textProperty = property.toString();
if (StringUtils.hasText()) {
properties.add(textProperty);
}
}
Usage:
addProperty(article.getTxtText());
// ...
Why are you doing this in a try / catch, just use simple if
if ( txtText != null ){
...
}
if ( txtLongText != null ){
...
}
I'm using Apache Xalan (v.2.7.1) to translate XML to XHTML in Apache Tomcat (v6.0.32). Sometimes the loading gets cancelled by the client and the following exception is thrown:
javax.xml.transform.TransformerException: org.apache.xalan.xsltc.TransletException: ClientAbortException: java.io.IOException
at org.apache.xalan.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:636)
at org.apache.xalan.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:303)
...
I would like to catch the ClientAbortException-exception, so that it doesn't spam the log. However, how can I check if the exception is nested inside the ClientAbortException? I tried something like this:
...
} catch (Exception e) {
if (e.getCause() != null && e.getCause().getCause() instanceof org.apache.catalina.connector.ClientAbortException) {
//do nothing
} else {
throw e;
}
} finally {
...
But it only gives me a nullpointerexception as the first getCause doesn't have a getCause. Any ideas?
Use the ExceptionUtils.getRootCause(Throwable) method in Apache Commons-lang, it will traverse the cause chain for you.
If getCause() is returning null, then the javax.xml.transform.TransformerException doesn't actually have a cause. When the Exception is created, you need to specify the cause, and they probably haven't done this. You probably can't do anything about that.
You can check if the
One method could just be to use a String match on Exception#getMessage:
...
} catch (Exception e) {
if (e.getMessage().contains("ClientAbortException:")) {
// at least log the error, in case you've got something wrong
} else {
throw e;
}
} finally {
...
However, this may be unreliable, for the obvious reason that it depends upon the text of the message.
EDIT: Thinking about it, you may find out in production that catching this exception is a bad idea, or that you've got the code wrong, so adding a method to turn on or off this behaviour may be a good idea:
...
} catch (Exception e) {
if (System.getProperty("abort.when.ClientAbortException") == null && e.getMessage().contains("ClientAbortException:")) {
// at least log the error, in case you've got something wrong
...
Then you at least have the option of turning off the code. The System.getProperty is just an example.
Use Like this. it's working fine.
catch (Exception e) {
if (e.getCause() != null && e.getCause() instanceof org.apache.catalina.connector.ClientAbortException) {
//do nothing
} else {
throw e;
}
}
Assume that I want to exit a console program if the user entered the char f, and in any time of the program.
The user is supposed to enter some info but I want for each step he entering the input to be able to stop all the operation if he entered "f"?
How can I do that?
Should it be something like:
try
{
if (userchoice.equals("F"))
{
throw new exception e;
}
}
catch (exception e)
{
System.exit(1);
}
Thanks
You can throw the exception, unless it is caught it will cause the current thread to die.
if ("f".equalsCaseIgnore(userchoice))
throw new IllegalArgumentException("Option "+userchoice+" not allowed.");
Here's the correct syntax:
try {
if (userchoice.equals("F")) {
throw new Exception();
}
} catch (Exception e){
System.exit(1);
}
Hint:
Scanner class
System.exit();
The input of the char "f" is expected behavior and so throwing an exception may be wrong way.
Encapsulate your input in a method which is responsible to handle the input and decided behavior.
Just call system.exit() here if the user entered "f" or call an exit method that does the work.
Do the following.
Read the input from the command line using classes like BufferedReader or Scanner.
Check for the character "f" from the i/p'ed string.
Throw your exception using throw new MyException();
Catch the exception in the catch block and terminate it with System.exit(1);
If you require "f" or "F", use equalsIgnoreCase() function.
Try something like this,
try{
if (userchoice.equals("F")) {
throw new MyException;
}
}
catch (MyException e) {
System.out.println("MyException caught because i/p character was F" + e);
System.exit(1);
}
I have something similar to this.
void func() {
try {
//socket disconnects in middle of ..parsing packet..
} catch(Exception ex) {
if(!ex.getMessage().toString().equals("timeout") || !ex.getMessage().toString().equals("Connection reset")) {
debug("Exception (run): " + ex.getMessage());
ex.printStackTrace();
}
}
Why is it that when I get a connection reset exception or a timeout exception, it still goes inside the condition. I tried without toString and with no luck.
You shouldn't catch all exceptions and then test the error message of the exception. Instead only catch those exceptions that you intend to handle - for example SocketTimeoutException.
catch (SocketTimeoutException ex)
{
// Do something...
}
With your current code you may be catching some other type of exception that you weren't expecting. Currently you will just ignore this exception, not even logging it. This can make it very difficult to debug what is going on. If you have an exception that you can't handle you should either rethrow it or log it.
I want to catch all exceptions
If you really want to do that then you can write your code as follows:
catch (SocketTimeoutException ex)
{
// Do something specific for SocketTimeoutException.
}
catch (Exception ex)
{
// Do something for all other types of exception.
}
Regarding your specific error, you have written:
!a.equals(b) || !a.equals(c)
This expression always evaluates to true. What you meant was:
!a.equals(b) && !a.equals(c)
Or equivalently:
!(a.equals(b) || a.equals(c))
Note that by rewriting your code as I suggested above you completely avoid having to write this complicated boolean expression.
It's really not safe to rely on exceptions messages to know what is the cause of your exception.
In your case you can try to catch more specific exceptions, such as SocketTimeoutException and the classic IOException :
void func() {
try {
//socket disconnects in middle of ..parsing packet..
} catch(SocketTimeoutException ex) {
//In case of Time out
} catch(IOException ex){
//For other IOExceptions
}
}
Sources :
[Socket.connect()][3]
Even if you prefer to seek informations in exceptions messages, you shouldn't check if the message simply is equal to "timeout" but if the message contains "timeout"
[3]: http://download-llnw.oracle.com/javase/6/docs/api/java/net/Socket.html#connect(java.net.SocketAddress, int)