ndemir
ndemir

Reputation: 1911

Error Handling Trade-Off in Java

There are two ways of error handling:

1) Use nested If and check errors

2) Use try/catch

Here is tutorial about this. But it is said here that try/catch hurts the performance. So, it seems there is a trade-off. How to decide? What should be done?

Upvotes: 3

Views: 436

Answers (4)

lauwie
lauwie

Reputation: 301

When creating/running an application you will always have some technical (network, io, os) and functional errors (i.e. programming/user).

Normally the handling of these errors should have been covered by the requirements (in real live not in academic space). When in doubt you should ask the client or functional architect.

You can be academic about this, but just follow the requirements and throw or swallow ;-).

Upvotes: 0

groundh0g
groundh0g

Reputation: 406

+1 for Mr. Skeet's answer. I'd like to add that your question implies an either/or situation, which it's not.

Try/Catch is only a performance concern if it's your sole method of handling errors. You need to ALSO use if/else to handle common, known cases. Save exception handling for exceptional cases.

For example, you can't predict out of memory errors, dropped network connections, or file corruption. In those cases you'd use try/catch.

Upvotes: 0

DaveFar
DaveFar

Reputation: 7467

I'd say (premature) optimization is the root of all evil. So for exceptional behavior, I'd always go with try/catch!

Upvotes: -1

Jon Skeet
Jon Skeet

Reputation: 1504004

Exceptions hurt performance if you use them badly. Don't use them for things which are bound to come up all the time, and they're fine.

Basically, you should use exceptions when something is wrong - and typically when something's wrong, performance isn't terribly important. On the other hand, if you have to put all your error checking in manually, the chances of something going wrong are somewhat higher, IMO...

Upvotes: 5

Related Questions