Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Being specific with Try / Catch

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?

like image 564
Ralt Avatar asked Dec 28 '12 17:12

Ralt


People also ask

Should everything be in a try-catch?

Putting everything in a try/catch statement is usually a sign of an inexperienced developer who doesn't know much about exceptions IME.

Is try-catch a good practice?

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)

Why try-catch is important?

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.

Does Try-Catch affect performance?

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.


2 Answers

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.

like image 96
usr Avatar answered Oct 21 '22 19:10

usr


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.

like image 23
Michael Bray Avatar answered Oct 21 '22 19:10

Michael Bray