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 trial

C#

Anuj Bhusari
Anuj Bhusari
12,240 Points

What is the need to catch each and every exception separately or uniquely?

I wanted to know why we catch different exceptions separately, why can't we just catch each and every exception using catch(System.Exception)?

2 Answers

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Anuj,

Well, you're not doing anything syntactically wrong, but you are going against how you are meant to use the exception classes. You are expected to use the appropriate subclass os System.Exception and not the base class directly. See what Microsoft themselves have to say on the matter.

Cheers

Alex

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Anuj,

When we write a try block, it's because we anticipate a particular kind of failure. However, it's possible that there might be a failure for a reason we didn't anticipate and the code we wrote to handle the expected failure is probably not ideal for handling the failure we didn't expect. By being very specific with our catch code, we will still get a crash for unhandled exceptions which will enable us to debug at the location where the error occurred. If we accidentally handle the wrong exception, we might continue execution with bad data that could cause a crash somewhere very distance from where the error occurred, making debugging extremely difficult.

Hope that helps

Alex

Anuj Bhusari
Anuj Bhusari
12,240 Points

Yeah, but what if we catch every exception with System.Exception? We aren't doing anything wrong, are we?