Being new to programming I have only just found out that you can specifically catch certain types of errors and tie code to only that type of error.
I've been researching into the subject and I don't quite understand the syntax e.g.
catch (InvalidCastException e)
{
}
I understand the InvalidCastException
is the type of error being handled, however I am unsure of what e
is.
Could somebody please explain this?
Putting everything in a try/catch statement is usually a sign of an inexperienced developer who doesn't know much about exceptions IME.
It's considered best practice to put as little code as possible in each try / catch block. This means that you may need multiple try / catch blocks, instead of just one. The benefits of this are that: it's easy to see which code raises which exceptions (and which code doesn't raise exceptions)
The try statement is used to define a block of code to be tested for errors while it is being executed. Whereas, the catch statement is used to define a block of code to be executed if an error occurs in the try block.
In general, wrapping your Java code with try/catch blocks doesn't have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM must perform to locate the proper handler for the exception.
Suppose there was no e
. How would you obtain the message of the exception?
The name e
(or any other name) is there for you to get a handle on the exception object so that you can extract information from it.
It is legal syntax not to give out any name:
catch (InvalidCastException) //legal C#
This works, but you can't know anything else about the error except its type.
The e
is the object that holds the data specific to the exception. If you look into different types of exceptions, you'll see that they all have different type of data. Many don't, but many do, and when they do, they can help you identify just exactly what happened instead of just getting a generic error.
For example, the NotFiniteNumberException
defines an additional property called OffendingNumber
that isn't present in a normal Exception
object... This then provides additional data that you might need to figure out exactly what happened.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With