Handling Exceptions in C# - When to catch them, where to catch them, and how to catch them

Handling Exceptions in C# - When to catch them, where to catch them, and how to catch them

IAmTimCorey

6 лет назад

170,315 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

@AliMustafa-xp8ih
@AliMustafa-xp8ih - 02.12.2023 19:13

what a great tutorial , Thank you TIm

Ответить
@user-pz1cd8lv3n
@user-pz1cd8lv3n - 07.11.2023 13:18

Thanks for amazing through content. you explain with simple examples the little details that come with the experience of the years.

Ответить
@demps1bm1
@demps1bm1 - 01.11.2023 17:38

Great video. I've known the mechanics of try/catch forever, but not the best practices, which you covered. One thing that you can do with try/catch is dealing with expected errors. I had a case where I had a text file of over a million records, of which 70%+ I knew would be defective. It was a console app that I threw together quickly to separate good data from bad. I used try/catch to log the error records but it also enabled me to keep my app running. In this case, I did not want the app to stop at all, even if there was an error (and in this case some 700k or more records were, as expected, bad.) Anyway, all of your advice is exactly right -- especially throw; which maintains the critical call stack. Thank you so much!

Ответить
@GnomeEU
@GnomeEU - 22.10.2023 04:45

Ex.ToString() has everything you need.
Your code looks scary.

Ответить
@AlejandroHernandez-ru1zz
@AlejandroHernandez-ru1zz - 05.10.2023 22:50

As always a great content Tim. This is what I like your videos, you don't just show how to use things, you also explain with simple examples the little details that come with the experience of the years.

Ответить
@gangstaqualified6777
@gangstaqualified6777 - 25.08.2023 05:39

Very good video

Ответить
@akab211
@akab211 - 07.08.2023 19:27

Gotta catch em all!

Ответить
@harvey_04
@harvey_04 - 02.08.2023 17:24

Thanks for the video

Ответить
@tanws8
@tanws8 - 04.07.2023 09:20

do you have a MVC webpage with exception handling video? sometimes I encountered an error in my page that causes the error message (for example Object reference not set to an instance of an object etc) to display on the browser which can be unprofessional in the real life.

Ответить
@andreivarga8440
@andreivarga8440 - 21.06.2023 13:09

So is better to use more catch blocks when we might face more exceptions, right? I think if we use just an catch(Exception ex) we could catch all of them there but can't treat each exceptions in a particular way. It would be weird to check for all exceptions inside an catch(Exception ex) with some if statements and then return something from there? And another quick question, is it ok to return something from try blocks?

Ответить
@swapnilpakolu4395
@swapnilpakolu4395 - 13.05.2023 18:52

Thanks for great explanation!!

Ответить
@pedromouro4046
@pedromouro4046 - 20.04.2023 10:42

Hi Tim, i am a begginer on master course, and i am confused when to use the exception. Exemple: when i ask a user for a int number, i receive the imput on a string and them use try.parse to check if is a int. If not i do a console.write saying that is a invalid number. So if i did not do the example, can i use a try catch for that validation? Or is not the best practice?

Ответить
@DanneManne88
@DanneManne88 - 14.04.2023 20:20

Verry good video! :)

Ответить
@ChiefsFanInSC
@ChiefsFanInSC - 14.02.2023 05:21

This is a great video!

Ответить
@Earan
@Earan - 08.01.2023 16:01

Hey, I was wondering, Why are you doing a weird complicated loop setup to output the Exceptions message and StackTrace, when a single ex.ToString() would've given you the same?

Ответить
@techbrojoe
@techbrojoe - 31.12.2022 00:35

Thanks for the video! I understood Try/Catch/Finally at a fundamental level and implemented them before. However, the throw; versus throw ex; and how the stack traces work depending on where you have the try/catch was something I never realized until watching this video and your explanation.

Ответить
@octavianbreazu8486
@octavianbreazu8486 - 13.12.2022 01:15

One of the most effective and nice presentations I have watched. I return to it from time to time to refresh my mind.
Thank you.

Ответить
@jacanaro5735
@jacanaro5735 - 02.12.2022 23:33

exactly what i needed

Ответить
@johng5295
@johng5295 - 23.10.2022 07:56

Thanks in a million.

Ответить
@interiorecology
@interiorecology - 15.09.2022 04:37

This is such a good video. Beyond explaining exceptions, that surround with tool is gonna be so handy.

Ответить
@byolock6244
@byolock6244 - 13.09.2022 13:46

What would be an appropriate way if you have like 10 code lines each adding a user to a group. Now the third line throws an exception but I actually want the code to continue and only after the user has been added to all the groups, I want to notify the user of the application of the failed attempts? If I use try catch the moment the third line fails it will jump into the catch block and therefore cancel all remaining commands to add a user to a group.

In my specific case it makes totally sense to just notify the app user so he can then try to add the user to the group(s) manually.

Ответить
@Blade17534
@Blade17534 - 04.08.2022 13:22

I have a quick question. If the caller is handling these exceptions, in te callee do you catc and just throw again?

Ответить
@AhmadElkhouly
@AhmadElkhouly - 15.07.2022 11:55

Thanks Tim. But why we handle these exceptions if we can prevent them? Are there exceptions that cannot be prevented through data validation? I speak from an indie programmer point of view.

Ответить
@knockedgoose4206
@knockedgoose4206 - 28.06.2022 01:03

This channel has been a huge help to me as a beginner programmer. I picked up a book on C# and although it outlines a good path of learning, and has taught me a lot of basic concepts, it really doesn't go into the "why" of a lot of things.

Many thanks Tim, it is clear that you are a mentor to many, and I appreciate that you put out tons of free content like this to help people improve.

Ответить
@anthonysteinerv
@anthonysteinerv - 27.06.2022 04:54

Guess this is why no one uses them lol, so much boilerplate, makes code less readable, makes code a mess, and ofc it adds another indentation level... Can't believe so many years have gone since Exceptions where invented, and no one has came with a better way of doing stuff, so people are actually encouraged to use them, because ofc it's not only about how ugly they are, but also takes performance to make your code harder to read? Sheesh.

Ответить
@AxelKohler98
@AxelKohler98 - 16.06.2022 17:42

So if I understand correctly, there is not really a difference between `finally` and the `catch` block (before any `throw` or other breaking/returning statement) as long as there is only a single `catch` block, correct?

Ответить
@haozheng8400
@haozheng8400 - 28.05.2022 17:27

This course is so so so great!!! Thank you so much!
1. It's better to let your application crash than eat the error and leave your code in an unknow state.
2. Put the "try...catch..." as high as possible so we can get the full call stack message in stack trace.
3. The difference between "throw" && "throw ex" && "throw new Exceptions("message")"
4. Different type of exceptions(eg: ArgumentException)
5. If we have multiple catch in one function, it will come to the first catch that matches.

Ответить
@octavian9168
@octavian9168 - 21.05.2022 03:46

Thanks!

Ответить
@trustingod0
@trustingod0 - 20.05.2022 07:14

@IAmTimCorey obviously you are a very experienced developer and also a Great Teacher. Correct me if I am wrong but isnt the try catch finally block generally used when you are accessing resources such as making a connection and read writes to the DB or reading and writing to a file? Also could you provide some clarity in regards to what you mean by "bubbling up". Thanks !!!!

Ответить
@karimmessaoud8223
@karimmessaoud8223 - 12.05.2022 08:49

Very good explanation. Thank you.

Ответить
@surajdengale9098
@surajdengale9098 - 12.05.2022 02:06

you are amazing

Ответить
@michaelvenero1509
@michaelvenero1509 - 17.03.2022 19:27

Great video thank you.

Ответить
@PabloMateoDrappo
@PabloMateoDrappo - 11.03.2022 17:53

Amazing video. Very useful! Thanks Tim. I click lik, comment and suscribed.. I do my homework. haha

Ответить
@simonbaxter8001
@simonbaxter8001 - 18.02.2022 12:24

Due to the performance hit of Exception handling, isn't the real solution to bounds check the 'position' value before using it to index the array? The big issue I see with coders these days is that they are getting lazy when it comes to validating bounds and particularly checking if objects (and pointers in C) are null before using them. I've been writing C and C# applications for 30+ years and never used Exceptions once. Good code isn't about handling errors, but putting sanitation/validation/tests in place to prevent them in the first place and handle them gracefully!

Ответить
@Greebstreebling
@Greebstreebling - 10.02.2022 02:26

Thank you very much for this clear and helpful explanation, really useful.

Ответить
@mohammadranjbaran1897
@mohammadranjbaran1897 - 28.01.2022 09:33

Thank you very much Tim.

Ответить
@arpitajoshi190
@arpitajoshi190 - 21.01.2022 21:21

Thank you for this helpful video! Was wondering if you could also do a video on what makes a program execution stop? Like 'break' etc keywords

Ответить
@alanbaird4543
@alanbaird4543 - 18.01.2022 05:54

Thanks

Ответить
@drip888
@drip888 - 16.01.2022 15:30

why are we not using this
int[] numbers = { 1, 4, 7, 2 };
instead of this
int[] numbers = new int[] { 1, 4, 7, 2 };

Ответить
@attilalaszlo782
@attilalaszlo782 - 09.01.2022 21:37

It is a super clear explanation about try-catch. Thank You!

Ответить
@attilalaszlo782
@attilalaszlo782 - 09.01.2022 21:34

Köszönjük!

Ответить
@Barrosy
@Barrosy - 06.01.2022 23:30

I had some fun discussion with one of my teachers about the fact that using exception handling may cause your application to do more work than it's supposed to. Exceptions themselves are classes containing a bunch of logic, which the application requires time and processing power to go through. Sometimes it might actually not be feasible to use exception handling. My question then would be, what are good examples/scenarios of when to refrain from using exception handling? The discussion was long ago and I like to watch your videos as refreshers/reminders.

Ответить
@BijouBakson
@BijouBakson - 02.01.2022 13:27

This is as far as I am concerned, very thorough and net. Subscribed. Thank you so much.

Ответить
@mahmoud19901990
@mahmoud19901990 - 06.11.2021 18:21

What is the best way to deliver the exception to the programmer when the app is at production?

Ответить
@ghevisartor6005
@ghevisartor6005 - 02.11.2021 04:05

I'm kinda struggling with this in blazor. Since you dont have controllers, most of the time, you inject your repository service/db context into the components and then you could either:
- put try catch on every of these methods
- return true or false for these operations while logging the reason for failing with if statements in the db (like if(user is null) log("user with id 'id' not found") and then show an error on the ui.
- return a dto from those method with a more detailed error that you arent able to get with validation alone.

I prefer to have the exception be thrown and crash the app because these situation should never happens, validation should take care of most bad inputs but not having a public api for example a GetUserById should always find the user. Unless someone else deleted that user i guess but you dont give that opportunity to users.
Maybe if they have shared notes that they can delete yes, the note could be requested just while someone deleted it. But in that case you should have events that update the ui?
Idk what do you think?

Or let's switch to ReactiveUi, use Observables and be done with it lol.

Ответить
@amortalbeing
@amortalbeing - 15.10.2021 14:36

Thanks again, it would be a good idea if you could mention that throwing/handling exception is an expensive operation and its best to always try to avoid one (raising exception), unless proven otherwise.

Ответить
@wafaza7934
@wafaza7934 - 30.09.2021 10:35

thanks, bro your explanation is excellent

Ответить