1

Recently, I was studying about throwing our own exceptions and I thought that maybe we can use if-else to check for the "suspicious" code and then deal with it in the if block. In the corresponding else block, we may proceed as if no exception arises..


I know it may be a bit difficult to use an if statement to try catching all the exceptions but it is possible. Plus, I guess it will also be better in terms of memory usage as I have heard that try-catch blocks are very expensive in terms of memory usage.

Radu Murzea
  • 10,724
  • 10
  • 47
  • 69
Chitransh Saurabh
  • 377
  • 6
  • 12
  • 23

3 Answers3

3

Actually in old languages there were no try...catch keywords and you should always use your own ways to deal with exceptions (yes, if-else could be used).

But today in languages like Java for example there are pieces of code where you MUST use try/catch because of checked exceptions. So depending on the language and what you are coding you can't completely stop using try...catch blocks.

http://en.wikipedia.org/wiki/Exception_handling#Checked_exceptions

ceklock
  • 6,143
  • 10
  • 56
  • 78
0

The idea of the Try / Catch is that it "catches" any errors you may have missed specifically coding for. I personally feel you should try to explicitly code for all conditions you can foresee and then use Try/Catch to handle errors you didn't foresee (and there will always be some of these).

Guy Hollington
  • 566
  • 5
  • 4
0

Exceptions are handled by the JVM; it's impossible for clients to ignore a checked exception.

You can add any validation of "suspicious" code you like, but you should still use try/catch where needed.

Write the proper idiom of Java. I see no advantage to your scheme, and it's likely to be confusing to anyone who has to maintain your code after you. (That poor person might even be you in 6-12 months.)

duffymo
  • 305,152
  • 44
  • 369
  • 561