Should I only include the code that's going to cause an exception inside of a try brace?

sock1992

Well-known member
Joined
May 20, 2020
Messages
107
Programming Experience
Beginner
I know...that title sounds stupid, but I just wanted to clarify something. At the moment I have all of my code inside of a try brace, even through the only part of the code that it likely to cause an exception would be the input of CustomerID. Should i only include the Customer ID input inside of the try brace? or doesnt it matter?
 
Last edited:
Generally speaking, yes. Doing so makes it clearer where an exception might be thrown. If you have loads of code inside the try block then it's easy to get confused about what part of the code you're guarding. The advantage of putting all the code in the try block is that the remaining code will be automatically skipped if an exception is thrown. Otherwise, you might need to add a return statement to the catch block or the like.
 
Also, you can avoid the exception altogether by using int.TryParse() instead of int.Parse().
 
Back
Top Bottom