Java exception handling get console error message - java

I want to get error message using java when exception are generated.
now I have java code with following scenario:
method first(){
try{
second();
}catch(Exception e){
System.out.println("Error:> "+e)
}
}
method second(){
try{
my code
}catch(Exception e){
throw new Exception("Exception generate in second method",e);
}
}
now when the first method execute then I get only "Exception generate in second method" message but there is some other message printed on console by java so how to get that console error message.
Note: I have already try with e.getMessage(); and e.printStackTrace();

Every exception has a cause that you can get with getCause(). You can go recursively down them until you get to the root cause. Here is your example with a utility that dumps the exception with all its causes like the console does.
private void first() {
try {
second();
} catch (Exception ex) {
Log.e("CATCH", getExceptionDump(ex));
}
}
private void second() {
try {
throw new UnsupportedOperationException("We don't do this.");
} catch (Exception ex) {
throw new RuntimeException("Exception in second()", ex);
}
}
private String getExceptionDump(Exception ex) {
StringBuilder result = new StringBuilder();
for (Throwable cause = ex; cause != null; cause = cause.getCause()) {
if (result.length() > 0)
result.append("Caused by: ");
result.append(cause.getClass().getName());
result.append(": ");
result.append(cause.getMessage());
result.append("\n");
for (StackTraceElement element: cause.getStackTrace()) {
result.append("\tat ");
result.append(element.getMethodName());
result.append("(");
result.append(element.getFileName());
result.append(":");
result.append(element.getLineNumber());
result.append(")\n");
}
}
return result.toString();
}

The message in the Exception constructor argument is not printed in the exception detail.
You can simply use this code to print the message :
method first(){
try{
second();
}catch(Exception e){
System.out.println("Error:> "+e.getMessage())
}
}
Hope this solves your problem

Why you cannot use print stack trace ?
Because A throwable contains a snapshot of the execution stack of its thread at the time it was created. (see Throwable)
It implies that, if you want to print the stack trace you need to use the printStackTrace() method BUT in your second method !
method second(){
try {
my code
} catch(Exception e) {
e.printStackTrace();
throw new Exception("Exception generate in second method",e);
}
}
Or using a the tricky method setStackTrace and using the printStackTrace() in first
method second(){
try {
my code
} catch(Exception e) {
Exception ex = new Exception("Exception generate in second method",e);
ex.setStackTrace(e);
throw ex;
}
}
method first(){
try {
second();
} catch(Exception e) {
e.printStackTrace();
}
}

You can print the cause of the exception you get. Try this:
method first(){
try{
second();
}catch(Exception e){
System.out.println("Error:> "+e);
if (e.getCause() != null) {
System.out.println("Cause:> " + e.getCause());
}
}
}

I believe this is the console message you want to achieve:
Error:> java.lang.Exception: Exception generate in second method
Try this code, when the catch block of the second method throws an exception the second method should declare it as throws or put a nested try catch within the catch block.
The exception is propagated to the first() method which is handled by its catch block.
public class Test {
public void first() {
try {
second();
} catch (Exception e) {
System.out.println("Error:> " + e);
}
}
public void second() throws Exception {
try {
throw new Exception();
} catch (Exception e) {
throw new Exception("Exception generate in second method", e);
}
}
public static void main(String ars[]) {
Test test = new Test();
test.first();
}
}

Related

Java Try Catch Exception

My current block of codes returns an exception like:
Exception occurred in API invocation A1-123 Fatal error
Caused by: A9-001 ColName is not found in TableName
but I would like to...
get rid of A1 Exception
show A9 Exception directly
not show A9 Exception in Caused by
How do I make the exception look like this?
Exception occurred in API invocation A9-001 ColName is not found in TableName
<no Caused by clause>
This is my sample code:
public Sample Method (Input input) throws AException
{
con = getSQLConnection();
try{
//do something
if(x==null){
throw new AException(A9ErrorMessages.A9_ERROR_FROM_TABLE, new String [] { "ColName", "TableName"});
}
}
catch (Exception e){
logger().error(e);
throw new AException(e);
}
finally{
if(con!=null){
try{
con.close();
}
catch(Exception e){
logger().error(e);
throw new AException(e);
}
}
}
}
Would it work if it's something like this:
try{
//do something
}
catch (Exception e){
logger().error(e);
throw new AException(A9ErrorMessages.A9_ERROR_FROM_TABLE, new String [] { "ColName", "TableName"});
}
catch (Exception e){
logger().error(e);
throw new AException(e);
}
I'm assuming the error that you want to catch and pass on is an AException - otherwise what you're asking for would violate the contract of the method. You could achieve what you're wanting with an extra catch clause like this.
try {
// whatever
}
catch (AException ae) {
throw ae;
}
catch (Exception e){
logger().error(e);
throw new AException(e);
}
finally {
// whatever
}
That way, only exceptions that are not already of type AException will get wrapped in new AException objects.
the first commenter is correct. i was able to do it by creating a new first catch:
public Sample Method (Input input) throws AException
{
con = getSQLConnection();
try{
//do something
if(x==null){
AException ae = new AException(A9ErrorMessages.A9_ERROR_FROM_TABLE, new String [] { "ColName", "TableName"});
logger().error(ae);
throw ae;
}
}
catch (AException ae){
logger().error(ae);
throw ae;
}
catch (Exception e){
logger().error(e);
throw new AException(e);
}
finally{
if(con!=null){
try{
con.close();
}
catch(Exception e){
logger().error(e);
throw new AException(e);
}
}
}
}

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 specify a message on a method "throws" in Java?

Im trying to return a JOptionePane message dialog for each one of the possible throws on my method:
public void add_note(String note) throws FileNotFoundException, IOException, InvalidFormatException{
... content ...
}
Is there any way to do this?
You could try something like :
public void add_note(String note) throws FileNotFoundException, IOException, InvalidFormatException
{
try
{
...content...
}
catch(FileNotFoundException fnfEx)
{
throw new FileNotFoundException("File was not found");
}
catch(IOException ioEx)
{
throw new FileNotFoundException("I/O exception");
}
catch(InvalidFormatException invEx)
{
throw new FileNotFoundException("Invalid format errror");
}
}
Where you put the message you want in the new exceptions and you print the exception message in the JOptionPane.
wrap your code inside try catch. Inside catch block for each exception type throw the message specific to each exception
Using a Try-Catch you can catch any exception and return something when an exception occurs. You should do this for all of your cases.
public void add_note(String note){
try {
//code
} catch (FileNotFoundException e) {
//return something
}
}
Instead of throwing exceptions, handle each individually in your method:
public JOptionPane add_note(String note) {
try {
...
} catch (FileNotFoundException fnfe) {
return ...;
} catch (IOException ioe) {
return ...;
} catch (InvalidFormatException ife) {
return ...;
}
}
I'll suggest you an alternative approach, as no one mentioned it.
I'd use AOP to catch those exceptions and show to the end user. You'll write a simple aspect, and dont mess your code with try and catch blocks.
Here is an example of such aspect
#Aspect
public class ErrorInterceptor{
#AfterThrowing(pointcut = "execution(* com.mycompany.package..* (..))", throwing = "exception")
public void errorInterceptor(Exception exception) {
if (logger.isDebugEnabled()) {
logger.debug("Error Message Interceptor started");
}
// DO SOMETHING HERE WITH EXCEPTION
logger.debug( exception.getCause().getMessage());
if (logger.isDebugEnabled()) {
logger.debug("Error Message Interceptor finished.");
}
}
}
If you don't know what Aspect Oriented Programming is definitely go check it out, this is very powerfull concept (just like OOP), spend some time to learn it.
If you want to show a dialog with the JOptionPane.showMessageDialog do as follows:
public void add_note(String note){
try {
//code
} catch (FileNotFoundException | IOException | InvalidFormatException e) {
JOptionPane.showMessageDialog(frame, e.getMessage(), "Title", JOptionPane.ERROR_MESSAGE);
//manage the exception here
}
}

Java IO Exception handling

when I debug the below code, there is an SmbException and goes catch block line sb.append(pLogger.reportError(pStr, e));, but it does not go into the method reportError().
what is the reason behind this. please advise if any changes.
try {
sfos = new SmbFileOutputStream(sFile);
} catch (SmbException e) {
sb.append(pLogger.rError(pathStr, e));
}
below is rError() method
public String rError(String pxString,Exception e){
String errorToMailStr=null;
abcd="Verifying # "+pxString+"::Error ["+e.getMessage()+"]";
logger.debug("Error when verifying # "+pxString+":Error ["+gMsg(e)+"]");
return abcd;
}
at line logger.debug("Issue "+pxString+":Error ["+gMsg(e)+"]");
is going to below method and ends.
public abstract class ReflectiveCallable {
public Object run() throws Throwable {
try {
return runReflectiveCall();
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
Based on what you have revealed here, there is a problem in getExceptionMsg()

IOException can not be resolved to a type error

For my final in Java we have a "exceptions" part on the test with try, catch, and finally calls. When I try to put the example code into Eclipse I get errors in the catch and throw new areas. All of the errors say "Can not be resolved to type".
How do I fix this so I can learn/review what the code is supposed to be doing?
Q4 Class
public static void main(String [] args)
{
Q4Exception q1 = new Q4Exception();
try{
q1.sampleMethod();
try{
q1.sampleMethod();
}
//This catch does not throw an error
catch(RuntimeException es)
{
System.out.println("A");
}
//This catch below throws the error of cannot be resolved to a type
catch(IOException es)
{
System.out.println("B");
}
//This catch does not throw an error
catch(Exception e)
{
System.out.println("C");
}
finally{
System.out.println("D");
}
}catch(Exception e)
{
System.out.println("E");
}
finally{
System.out.println("F");
}
}
Q4Exception Class
public void sampleMethod() throws Exception
{
try{
throw new IOException("H");
}
catch(IOException err)
{
System.out.println("I");
throw new RuntimeException("J");
}
catch(Exception e)
{
System.out.println(e.toString());
System.out.println("K");
throw new Exception(“L");
}
catch(Throwable t)
{
System.out.println("M");
}
finally{
System.out.println("N");
}
}
I think it's worth mentioning that in Eclipse, Ctrl+Shif+O does the job of resolving the imports for you.
Oh, guess I could answer my own question here.
Didn't know I had to import the IOException from java.io!
Easy to just use
import java.io.*
for the imports
I discovered I was using an old version of JWT , the issue is gone after using the a newer version of JWT dependency .

Categories

Resources