I am having a piece of code and in the catch block I intentionally add some piece of code as I am sure the flow will once come to catch.
So for a big project, is this type of coding leads to some more resource usage as logically if any exception occurs, lead to a new thread or hold in JVM so it means some resource utilization and I do have a way to avoid exception to occur and do the piece of code somewhere in proper place.
Let me clarify-
char ch = 'c'
try{
Integer.parse(character.toString(ch));
}(Exception e){
//SOME VERY IMPORTANT OPERATION LIKE LOGIC MATHEMATICAL BASED
}
Now the above piece of code will throw me NumberFormatException and inside the catch loop I added my piece of logic, Now the same thing I can avoid and write
char ch = 'c';
if(!Character.isDigit(ch))
//SOME VERY IMPORTANT OPERATION LIKE LOGIC MATHEMATICAL BASED
Now I didn’t write any exception but it will work properly.
Now my question, is the 1st approach of catch coding will lead to some internal resource usage , I mean does JVM internally leads to some internal resource usage and this kind of catch coding should be avoided as max as possible or I can definately use the 1st approach
It’s very hard to understand the question, but some general points:
Exceptions are for exceptional events. Exceptions should not be used for normal conditions. Throwing an exception is an expensive operation.
try/catch/finallyblocks are not resource-expensive at all. JVMs are optimized to handle them very efficiently, because properly-written code uses them all over the place.The cost comes in when an exception occurs, not when you use
try/catch/finallyin your code. So you should feel free to usetry/catch/finallyall over the place, but avoid writing code that relies on exceptions in the normal course of things.For instance, here’s a bad example of using exceptions:
This is bad because the method clearly says that passing in a
nullfooargument is a normal use case, but the code relies onfactory.getThingy(foo)throwing aNullPointerExceptionwhen you pass infoo = null. Since that’s a documented normal use-case, you code for it explicitly:The
try/finallyin that is not expensive. Throwing an exception is expensive.