java


What to do when catching e(rror) in Java


In Java, I see a lot of codes like below.
What I am wondering is, is it enough just to show error message?
I am new to Java. What I want to learn is how to handle error efficiently, and know best practices for error-handling. In general, what should I do in catch block?
Example 1 : printStackTrace()
} catch (SomeException e) {
e.printStackTrace();
}
Example 2 : getMessage
} catch (SomeException e) {
e.getMessage();
}
Example 3 : show custom error message
} catch (IOException E) {
System.out.println("Error occured. Please try again.");
}
In short, the answer is depends. Do what your business logic asking for.
If you want to log it, log it.
If you want to see the error in console, print it to there.
If you want to throw back to the method caller, go do it.
There are no of possibilities and needs depending on the situation.
I'd recommend you starting with Exception section in Java tutorial.
What you should do in the catch block depends on your application.
Generally, if you're just logging the error, you should include the stacktrace to make debugging easier.
logger.error("Error occurred.", e);
e.printStackTrace prints the message to the console, you can use this when the user sees the console...
e.getMessage() return a String, so you can handle as you wish, like:
try {
} catch (IOException E) {
System.out.println("Error occured. Please try again."+ e.getMessage());
}
or use the getMessage() when you have no console, but, for instance, a GUI, you can set:
textField.setText(e.getMessage());
You should log the error using a Logger so you can decide where to write the excetion (es. a file) and also do something else, depending what your code is doing.
For example if you are writing into a database you should rollback the data to the previous state.
I also suggest you not to suppresses the exception, but let the "user" know something went wrong. You can catch the exception and wrap it into another one with a message more user-friendly.
you can also redirect to another page like error page while getting any exception in the try catch block .
you can also describe the error on the html page .
so user redirect to the error page if there are exception in catch block.
e.printStackTrace();
the above could be good practice since it will trace the stack and show what and where the problem is

Related Links

Binary search tree, when the order of objects is created
Can't solve add(android.support.v4.app.Fragment) in List can not be applied to (make.application.Fragment)
Eclipse Checkbox Databinding in Gui class
Set hours minutes and seconds to 00 in ZonedDateTime or Instant
Why does Stream.reduce(BinaryOperator) throw NullPointer when the result is null?
JavaFX: Two values in one TableColumn
popping an element of a queue at initialisation of for loop ends up popping the same element all the time
If data gets updated in the db within catch time how to handle in hibernate?
Log file not rolling automatically in jetty 9.3.16
Formatting Integer with a decimal point
Thread.join() explanation
How to use stream#sorted() to sort by the product of two fields in Java 8
Is it possible to add customize method in String class? [duplicate]
Android Gradle Errors
partition in a singly linked list
Parse soap xml response to java Object

Categories

HOME
webpack
amazon-ec2
omnet++
octobercms
yahoo-oauth
paw-app
cross-browser
datastax-java-driver
azure-storage-tables
contact
amazon-cloudformation
session-variables
windows-10-universal
user-input
messages
ibm-odm
dynamics-crm-online
transformation
crystal-reports-2008
intentfilter
facebook-instant-articles
tapestry
zurb-foundation-6
smb
numerical-methods
minitab
gsoap
r-raster
media-queries
react-chartjs
exuberant-ctags
code-contracts
perlin-noise
bower-install
bytecode-manipulation
http-digest
vxworks
jquery-bootgrid
android-fingerprint-api
document.write
texmaker
ibpy
fakeiteasy
bootstrap-dialog
outlook-api
netcdf4
modelmapper
businessworks
wptoolkit
apache-fop
dropbox-php
git-diff
nstextview
slickedit
worker-thread
snmptrapd
typed-lambda-calculus
nsarray
media-player
pillow
sts-springsourcetoolsuite
mathematica-frontend
fputcsv
hill-climbing
goose
phpcas
mmc
dd
codeigniter-routing
internet-connection
aapt
balanced-payments
mysqltuner
c18
dbconnection
itmstransporter
sublist
dsn
wse3.0
bubble-chart
punbb
tomcat-valve
appender
self-extracting
lpeg
zend-translate
.nettiers
wise
gamma
rescale
kdbg
boost-smart-ptr
temporal-database
aquaticprime
document-conversion

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App