Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMarwa Almoqbali
639 Pointswhat is the use/purpose of try and catch in c#?
I don't know when I have to use try and when I have to use catch
2 Answers
Steven Parker
231,248 PointsYou would always use these together. The "try" block surrounds the code that might generate an exception (error), and the "catch" block contains the code that you want to run if an exception occurs.
James Edwards
4,862 PointsI had the same problem when I first saw it myself. Programming is very conceptual and sometimes it helps to just run the code in your head.
Try and catch statements are used to prevent an error from crashing the whole program.
So let's say we created a simple Console Application that asks the user to type in their name. If the user typed in a number and your next line of code was to greet the user with their input.. You don't want to tell the user Hello 3.14. Instead you would want to tell the user that a number is not a valid input.
This is a very simple example and there are other ways to fix that problem instead of using a try and catch statement. There are more complex examples where you would definitely want to make sure the error is caught.
Just think "try" and "catch", remember when I said programming is conceptual... You "try" some code that might cause and error and "catch" it with another line to prevent your code from crashing.
Hope this helps,
Cheers!
Marwa Almoqbali
639 Pointsthank you a lot it helps me. full answer and everything is clear,