How to get Exception Class from Exception Name - java

I have a string variable that has a full qualified exception name. I want to check in catch block if exceptions occur whether it is an instance of exception that mentioned in string or not. How to solve that
String stringEx = "org.hibernate.StaleStateException";
try {
// program
} catch (Exception ex) {
if (e instanceof stringEx) { //<-- How to convert string to exception class
// do specific process
}
}

Maybe you need this:
String stringEx = "org.hibernate.StaleStateException";
try {
// program
} catch (Exception ex) {
if (Class.forName(stringEx).isInstance(ex)) {
// do specific process
}
}

Related

Comparison of exception message always fails in if my statement

I have this variable in my Constants class:
public static final String EXCEPTION_STRING= "My Exceptions message";
I want to check for it in my catch and throw a particular message if it's found. This is what I came up with:
} catch (Exception e) {
if (e.getMessage().equals(Constants.EXCEPTION_STRING)) {
throw new ServiceException(MyClassName.class.toString(),
Constants.EXCEPTION_STRING);
} else {
LOGGER.info("Save failed: " + e);
}
}
The if never seems to get entered even though I can see the correct exception message. What am I doing wrong?
Does your own custom exception get wrapped in another exception? In that case you need to do something like:
e.getCause().getMessage()
This is what I did:
} catch (Exception e) {
if (e instanceof AxisFault) {
if (e.getMessage().equals(Constants.EXCEPTION_STRING)) {
throw new ServiceException(MyClassName.class.toString(),
Constants.EXCEPTION_STRING);
}
} else {
LOGGER.info("Save failed: " + e);
}
}

Get Method name with parameters and its values on exception in Java

I have a sample program as follows
public static void enterText(WebElement loc, String value) {
try {
loc.clear();
System.out.println("Text cleared successfully");
} catch (Exception e) {
// exception handling
}
}
On executing loc.clear(), a runtime exception occurs.
Is there a way I can get the method name with parameters after exception happens.
I need to get this enterText(WebElement loc, String value).
You shall print the trace of the exception via this call: e.printStackTrace() inside catch block.
You just need to add a "print" statement in the catch block.
public static void enterText(WebElement loc, String value) {
try {
loc.clear();
System.out.println("Text cleared successfully");
}
catch (Exception e) {
System.out.printf("ERROR: enterText( %s , %s )%n", loc, value);
e.printStackTrace();
}
}

Handle object mapper exception and missing return statement

I am contemplating throwing a RuntimeException inside the catch block to solve the missing return statement.
What would be way to handle this situation?
I think throwing an exception of some kind instead of return some meaningless value. .
private String tryObjMapper(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//missing return statement
}
It depends on what you want to be the fallback/default value or error handling
You have 2 main options (with 2 sub options):
1.A.Throw the exception:
private String tryObjMapper(Object obj) throws JsonProcessingException {
return objectMapper.writeValueAsString(obj);
}
1.B.Rethrow RuntimeException (or custom unchecked exception)
private String tryObjMapper(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException("Failed to map obj +" obj, e);
}
}
2.A.Define a default value on error
private String tryObjMapper(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;//or other default value
}
2.B.Define a default value with a single return statement:
private String tryObjMapper(Object obj) {
String retVal = null;//or other default value
try {
retVal = objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return retVal ;
}
Consider logging exception using logger and not using e.printStackTrace()
I think that the best way to handle it is to return null at both catch block ant the end of the function. You must check the returnee from the function whether null or not before usage.
Note: This solution is suitable if only you can't change the signature of the function to declare that it throws an exception. Otherwise, go with the signature update.

Get exception instance class name

I would like to know what the exception instance was in this situation:
try {
// some risky actions
} catch (Exception e) {
System.out.println("Get instance name there");
}
How can I achieve this?
Here you go:
try {
throw new ArithmeticException();
} catch (Exception e) {
System.out.println( e.getClass().getCanonicalName());
}
Output:
java.lang.ArithmeticException
The type of the exception is shown as part of the output of:
e.printStackTrace();
To get it programmatically you can use:
String exceptionClassName = e.getClass().getName();
It is poor form to have logic depending on exception sub types within a catch block. Sonar will flag this as a code violation (squid S1193).
Instead you should add multiple catch blocks to catch different types of exceptions:
try {
readFile(fileName);
}
catch (java.io.IOException e) {
LOG.error("Error accessing file {}", fileName, e);
}
catch (java.lang.IllegalArgumentException e) {
LOG.error("Invalid file name {}", fileName, e);
}
Note: Since Log4j 2 (and SLF4J 1.6+) you can add a throwable as the last parameter and it will be recognized as such. So the above will work!
Since Java 7 you can also do a multi-catch:
}
catch (java.io.IOException | java.lang.IllegalArgumentException e) {
LOG.error("Could not read the file {}", fileName, e);
}
The benefit of the multi-catch is that you can handle multiple exception types within a single catch block without having to revert to a common super class (like java.lang.Exception) that would include exception types you didn't want to handle.
Default exception logging is something like
try
{
//
}
catch (Exception e)
{
e.printStackTrace();
}
This will print the stacktrace of the exception to system.err
If you are looking to add some contextual information, you can take a look at Apache Commons ContextedRuntimeException
public static void main(String[] args) {
try {
doSomething();
} catch (ContextedRuntimeException e) {
System.out.println(e.getMessage());
System.out.println(e.getContextEntries());
}
}
private static void doSomething() {
int divisor = 0;
int dividend = 100;
int result;
try {
result = dividend / divisor; // Just throw an exception to test things....
System.out.print("DIVISION RESULT: "+result);
} catch (ArithmeticException e) {
throw new ContextedRuntimeException("Oops..division by zero not allowed", e)
.addContextValue("Divisor", divisor)
.addContextValue("Dividend", dividend);
}
}
would output:
Oops..division by zero not allowed
Exception Context:
[1:Divisor=0]
[2:Dividend=100]
---------------------------------
[(Divisor,0), (Dividend,100)]

How to return value and Exception (if it is there.)

I have helper class in which I have written this function.
public static String createProject(Map<String, String> params,String projectName, String projectPrefix) {
String createdProject = null;
try {
createdProject=//logic for creating createdProject string which may throw two exception mentioned below
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (TestLinkAPIException t) {
t.printStackTrace();
}
return createdProject;
}
now I am calling this function from GUI part where I have written
String createProject=//called above function.
now If error occur in above code I want to show error to the user.
my question is how I get back the created string and error message if some Exception occur
Create a Custom Exception
Add your String value as an instance field of that Custom Exception.
Throw the custom exception with the String values passed in.
Now you have the exception and the String as well.
If you have a Java 7, then you can use Multi-Catch exception block.
public static String createProject(Map<String, String> params,String projectName, String projectPrefix) throws Exception {
String createdProject = null;
try {
createdProject=//logic for creating createdProject string which may throw two exception mentioned below
} catch (MalformedURLException | TestLinkAPIException e) {
e.printStackTrace();
throw new Exception("Error creating createdProject", e);
}
return createdProject;
}
If exception occurs, createdProject is never set.
You should throw the exception from this method and catch it in block where you calling this method.
public static String createProject(Map<String, String> params,String projectName, String projectPrefix) throws Exception {
String createdProject = null;
try {
createdProject = doSomething();
} catch (Exception e) {
throw new Exception("Error creating Project");
}
return createdProject;
}
and where you calling this method you will have something like this.
try {
String str = createProject();
displayTheProjectCreated(str);
} catch (Exception e) {
// Oops something went wrong
displayErrorMessage(e);
}

Categories

Resources