What to do when catching e (rror) in Java

In Java, I see a lot of codes, as shown below. I am wondering if it’s enough to just show the error message?

I am new to Java. I want to learn how to handle errors efficiently and know the best error handling methods. In general, what should I do in the catch block?

Example 1: printStackTrace ()

} catch (SomeException e) { e.printStackTrace(); } 

Example 2: getMessage

 } catch (SomeException e) { e.getMessage(); } 

Example 3: show a custom error message

 } catch (IOException E) { System.out.println("Error occured. Please try again."); } 
+5
source share
6 answers

In short, the answer depends. Do what your business logic asks for.

  • If you want to register it, write it down.
  • If you want to see the error in the console, print it there.
  • If you want to return to the method call, do this.

Depending on the situation, there are no opportunities and needs.

+5
source

I would advise you to start with the Exception section in the Java tutorial .

What you should do in the catch block depends on your application.

Generally, if you are just reporting an error, you should enable stacktrace to make debugging easier.

 logger.error("Error occurred.", e); 
+2
source

e.printStackTrace displays a message on the console, you can use this when the user sees the console ...

e.getMessage () returns a string, so you can handle it as you like, for example:

 try { } catch (IOException E) { System.out.println("Error occured. Please try again."+ e.getMessage()); } 

or use getMessage () when you don’t have a console, but, for example, a GUI, you can set:

 textField.setText(e.getMessage()); 
0
source

You have to log the error using Logger so that you can decide where to write the excetion (like a file) and also do something else, depending on what your code is doing. For example, if you are writing to a database, you must roll back the data to a previous state.

I also suggest you not suppress the exception, but let the “user” know that something went wrong. You can catch the exception and transfer it to another, with a message more convenient for the user.

0
source

you can also redirect to another page, such as the error page, when you receive any exceptions in the catch try block. you can also describe the error on the html page. therefore, the user is redirected to the error page if there is an exception in the catch block.

0
source
 e.printStackTrace(); 

the above can be good practice as it will track the stack and show what and where the problem is

-1
source

All Articles