Getting error number of an exception object - java

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

Related

An exception is not thrown using throw command

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.

Exception Handling in Java to have Java best practices

I have a Java method like below:
private boolean getBooleanProperty(String property, String defaultValue) {
boolean result = false;
try {
result = Boolean.parseBoolean(properties.getProperty(property, defaultValue));
} catch (IllegalArgumentException | NullPointerException e) {
}
return result;
}
I know that the way I am handling the exceptions in above method is not correct and looking for the way to have those more aligned with the Java standards and best practices.
Similarly for the method below:
public void getStatusAndAnnotation(ITestResult result) {
try {
HashMap<Object, Object> map = new HashMap<>();
Method method = result.getMethod().getConstructorOrMethod().getMethod();
TestInfo annotation = method.getAnnotation(TestInfo.class);
try {
//add id removing the first character of the annotation (e.g. for C12034, send 12034)
if(annotation!=null) {
map.put("id",annotation.id().substring(1));
}
}catch (NullPointerException e){
e.printStackTrace();
}
if (result.getStatus() == ITestResult.SUCCESS) {
map.put("result", 1);
} else if (result.getStatus() == ITestResult.FAILURE) {
map.put("result", 9);
} else if (result.getStatus() == ITestResult.SKIP) {
map.put("result", 10);
}
if (annotation != null) {
if(annotation.trDeploy() && !map.get("id").equals(null) && !map.get("id").toString().isEmpty())
{
ApiIntegration.addTestResult(map);
}
else System.out.println("Deploying result was canceled, because test has annotation \"trDeploy: false\" or \"id\" has no value");
}
} catch (SecurityException | IOException
| ApiException | NullPointerException e) {
e.printStackTrace();
}
}
How do I handle these different exceptions to align with the best practices?
What I typically do is let the compiler/IDE tell me what exceptions I need to catch unless you want to catch an exception for a specific reason. That way, I can code without catching unnecessary exceptions and my code is cleaner.
These type of Exceptions are called Checked Exceptions
"In the Java class hierarchy, an exception is a checked exception if
it inherits from java.lang.Exception, but not from
java.lang.RuntimeException. All the application or business logic
exceptions should be checked exceptions."
Example:
try
{
// open a file (Compiler will force to either catch or throw)
}
catch (IOException ioe)
{
ioe.printStackTrace();
// need to make a decision on what to do here
// log it, wrap it in a RuntimeException, etc.
}
As for Unchecked Exceptions
"Unchecked, uncaught or runtime exceptions are exceptions that can be
thrown without being caught or declared"
Example:
String x = null;
// this will throw a NullPointerException
// However, you don't need to catch it as stated in some the comments
x.toString();
What you should do is prevent it
if (x == null)
{
x = "some default value"; // prevent the exception from happening.
}
x.toString();
Does this mean you should never catch a RuntimeException
No, of course not. It depends on the scenario.
Take this example:
String number = "12345";
// You don't know if number is a valid integer until you parse it
// If the string is not a valid number, then this code will
// throw an Exception
int i = Integer.parseInt(number);
Instead you can catch a NumberFormatException. Again, this is a form of prevention.
int i = 0; // some default
try
{
i = Integer.parseInt(number);
}
catch (NumberFormatException nfe)
{
// Good practice to log this, but the default int is fine.
}
Some Best Practices
Do not catch exceptions unless the compiler forces you to.
If you are catching a checked exception, then log it. You can also wrap it in a RuntimeException if you want it to percolate up the call stack.
If you want to catch a RuntimeException, then do so with a purpose (i.e. you can set a default and prevent the error all together.)
Don't have a chain of methods all throwing a checked Exception up the stack trace. This is very messing and forces all calling methods to either catch or throw the checked exception.
Catching a RuntimeException just to log it really doesn't have much of a purpose. Unless you are logging it in a catch all location.
Catch-All Example:
try
{
// entry point to application
}
catch (Throwable t)
{
// let all exceptions come here to log them
}

How do I display an exception?

I am checking if number the user entered is Zeckendorf and I want to display an exception if it is not, how do i do that? Also how do I convert the Zeckondorf to its decimal equivalent?
import java.util.Scanner;
public class IZeckendorfNumberConvertor {
static String number;
int zeckonderEquivalent;
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
convertToZeckonderNumber();
isTrueZeckonderNumber();
}
private static boolean isTrueZeckonderNumber() {
System.out.println("Enter a Zeckonder Number:");
number = scanner.nextLine();
if (number.equals("10100"))
{
return true; }
else if (number.equals("010011") || number.equals("010100"))
{
return false; }
return false;
}
private static void convertToZeckonderNumber() {
}}
I advise you not to display an exception (i.e. trace and such) as it is very user Unfriendly.
You can use the throw syntax to throw a proper exception :
throw new Exception("Given number is not a Zeckendorf number");
but be sure to catch it and display a nice and clean message :
try {
// Your input code goes here
} catch (Exception e) {
System.out.println(e.getMessage());
}
Another easier option will be to just check the return value of the method and print the results accordingly.
I will recommend to use the latter solution as exceptions are used when something bad and unexpected happens in your program and you want to handle it gracefully. In your case the behavior is expected (i.e. user giving a wrong number) so checking the return value will be much clean and easier.
Use try catch block for catch an exception
try {
} catch (Exception e) {
e.printStackTrace();
}
Also use throw for throw a new exception
Assuming to really do want to display the exception, and not a more user friendly message, the first step is probably to get the exception as a string. Then you can do what you like with that string (echo to console, place in a javax.swing.JTextArea, email it, etc).
If you just want the message from the exception, then getMessage() will do:
try { ... }
catch(FooException e) {
String msg = e.getMessage();
}
However, if you want the whole exception, stack trace and all, you'll want something like this:
public static String stackTrace(Exception e) {
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
return w.toString();
}
// ...
try { ... }
catch(FooException e) {
String st = stackTrace(e);
}
If you just want to echo the full stack trace to the console, there is the printStackTrace(), no-arg method:
try { ... }
catch(FooException e) {
e.printStackTrace();
}
If you want to take more control of the presentation of the stack trace you can get the details with:
try { ... }
catch(FooException e) {
StackTraceElement[] stes = e.getStackTrace();
// Do something pretty with 'stes' here...
}
You can just print a error message to the user saying that the input is wrong using a simple if.
if(yourCondition){
// Happy scenario
// Go shead
}else{
// Error Scenario
System.out.println("Error. Invalid Input.");
// If you persist to throw an exception, then you can do something like this
// throw new Exception("Exception Explanation"); // I've commented this, but you can uncomment it if needed
// But the advice is to display an error message, than throw a exception.
}
And regarding the conversion, you can convert binary to decimal like this
int i = Integer.parseInt(binaryString, 2); // 2 indicates the radix here, since you want to convert from binary.
With this code snippet you can convert the String into an integer :
int numberAsInt;
try {
numberAsInt = Integer.parseInt(number);
} catch (NumberFormatException e) {
//Will throw an Exception
}
If you want to create your own Exception class, you can do it like shown here or just throw a RuntimeException with
throw new RuntimeException("Your Message");
My opinion, you can try some thing like following
public static void main(String[] args) {
if(!isTrueZeckonderNumber()){
// your message should goes here
System.out.println("Your message");
}
}
If you really want to throws an exception do following
private static boolean isTrueZeckonderNumber() throws Exception{
System.out.println("Enter a Zeckonder Number:");
number = scanner.nextLine();
if (number.equals("10100")) {
return true;
} else{
throw new Exception("your message");
}
}
What do you mean you want to display an exception?
I would suggest just giving the user feedback instead, as exceptions are used more commonly for EXCEPTIONAL actions that are not supposed to happen.
However if you do want to, you can print a message explaining what happened.
try {
} catch (Exception e) {
System.out.println(e.getMessage());
}

How to catch a nested exception in java

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;
}
}

How to throw exception for statment?

HI !
I want to throw exception for the line
BarcodeNo=Long.parseLong(jTextField1.getText())
I done this in a way
BarcodeNo=Long.parseLong(jTextField1.getText()) throw new NumberFormatException("Enter Numbers Only ");
But this way compiler throws error stating ";" required
So anyone can tell me how to do this ?
Thanks
That will already thrown an exception if the text isn't in the right format. If you want to change the exception message, you'd have to catch the exception and throw a new one:
try {
BarcodeNo = Long.parseLong(jTextField1.getText());
} catch (NumberFormatException e) {
throw new NumberFormatException("Enter Numbers Only");
}
I wouldn't suggest that you try to use exception message as user-visible messages though - they're more reasonable for logging than for showing an end user.
yes you should put
try
{
BarcodeNo=Long.parseLong(jTextField1.getText());
}
catch(Exception e)
{
throw new NumberFormatException("Enter Numbers Only ");
}

Categories

Resources