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

Поделиться
HTML-код
  • Опубликовано: 5 сен 2024

Комментарии • 434

  • @knockedgoose4206
    @knockedgoose4206 2 года назад +5

    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.

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +1

      I am glad my content has been so helpful.

  • @DasturlashniOrganamiz
    @DasturlashniOrganamiz 4 года назад +10

    You were explaining bad practices with handling exceptions in the beginning.
    Me: That's exactly what I have been doing till this moment 🤦‍♂️
    Thanks, Mr. Corey for taking time for new developers like me. I really appreciate your content!

    • @IAmTimCorey
      @IAmTimCorey  4 года назад +1

      You are welcome. I am glad it was helpful.

    • @korsos68
      @korsos68 4 года назад

      That was exactly the same that happened to me today. Really useful video. Thanks Tim.

  • @haozheng8400
    @haozheng8400 2 года назад +3

    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.

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +1

      I’m glad you are getting so much value out of it.

  • @sanityinaseaofmadness7353
    @sanityinaseaofmadness7353 4 года назад +3

    As someone who's been working with C# for more than a decade, I have fun watching your material in this channel. I usually pick up 5-10% of it as corrections-to or suggestions-for the things I've been doing. I even learn something completely new to me from time to time. Nicely done, Tim.

  • @niloo195
    @niloo195 4 года назад +4

    Before watching this video, I was the one you mentioned in 37:00, who does not know the real purpose of catch! Thanks Tim! I am learning and learning and enjoying from your videos! Cheers!

  • @interiorecology
    @interiorecology 2 года назад +5

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

  • @buskilamaor9587
    @buskilamaor9587 3 года назад +5

    Wow, the best and the most detailed explanation (and non dumb "DivideByZero" exception explanation) which actually explained the whole stack call chaining and different reasons to throw \ catch \ handle exceptions...thanks man.

  • @RalfsBalodis
    @RalfsBalodis 4 года назад +8

    0:39 - building a demo console application
    9:49 - crashing the application
    11:13 - "try - catch" and how NOT to use it
    15:00 - continuing with the exception & showing exception information to the user (15:57 )
    17:24 - more useful information: StackTrace
    20:31 - "try - catch": best place to put it and why
    27:23 - hanging logic demonstration
    30:31 - the "finally" code block and "throw" statement. Passing exception up the stack (to UI)
    38:08 - common misconceptions and mistakes
    40:25 - creating new exception without loosing original StackTrace info
    45:36 - recap
    47:05 - advanced exception handling
    53:09 - summary and tips on value capturing and handling exceptions

    • @IAmTimCorey
      @IAmTimCorey  4 года назад +3

      Thanks! I added it to the description.

    • @RalfsBalodis
      @RalfsBalodis 4 года назад +1

      @@IAmTimCorey Thanks. Feel free to adjust some topic titles. I'm very new at c#. I might not have complete understanding how to describe something yet. Also, English is not my native language. I might not have the vacubolary ;)

  • @roadtoalaska-fuerzaucrania3549
    @roadtoalaska-fuerzaucrania3549 3 года назад +4

    This is the best youtube channel about C# !!!!

  • @stani1k
    @stani1k 3 года назад +2

    Until now I often catched exceptions at low level, but now I understand the problem and benefits of doing it at high level.
    That was really helpful, once again. Thanks!

  • @Trashcandogchoir
    @Trashcandogchoir 3 года назад +3

    Finally someone with a tolerable voice and cadence. Very soothing yet keeps the attention! Great work!

    • @IAmTimCorey
      @IAmTimCorey  3 года назад +2

      Thanks!

    • @rockymarquiss8327
      @rockymarquiss8327 3 года назад +1

      I agree - Tim communicates effectively and clearly. He is a good teacher and does a great jo.

  • @jonathanmcdermott25
    @jonathanmcdermott25 4 года назад +1

    Hi, current CS major with the world’s driest textbook for an online C# class here. Thank you SO much for your wonderful videos. There is something magical about seeing something in practice vs reading a hundred pages about exceptions.
    Getting a base understanding from your videos before trying to comprehend certain topics makes life WAY easier!
    Great channel. Glad to be a new subscriber!

    • @IAmTimCorey
      @IAmTimCorey  4 года назад

      Excellent! I'm glad my content is helping.

  • @Ruslakall
    @Ruslakall 4 года назад +27

    You missed out on a perfect pun. When you stated you didn't like abbreviations on variable names, you should have said "...but ex is the exception"

  • @Tarodev
    @Tarodev 8 месяцев назад +3

    I've always pointed people to this video, so I suppose I owe you, thanks.

    • @IAmTimCorey
      @IAmTimCorey  8 месяцев назад +2

      Thank you! Although, I don't consider you to owe me anything. I'm happy to be of help.

  • @bb579774
    @bb579774 3 года назад +1

    Another really fantastic video @IAmTimCorey. I am learning server side C# right now and your videos are always the first place I look. Thank you!

  • @techbrojoe
    @techbrojoe Год назад +1

    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.

  • @brianmoore9281
    @brianmoore9281 3 года назад +2

    Thanks Tim, as ever a very informative video. I am an experienced c# developer but even so its worth watching your videos as every now and again you learn something new - and in this case I discovered I have not been using the Finally clause properly!

  • @octavianbreazu8486
    @octavianbreazu8486 Год назад +1

    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.

  • @AlejandroHernandez-ru1zz
    @AlejandroHernandez-ru1zz 11 месяцев назад

    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.

  • @demps1bm1
    @demps1bm1 10 месяцев назад

    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!

  • @MusicToMyEar1005
    @MusicToMyEar1005 4 года назад +1

    This is what I learned from this: Coding of the exception handling part is as important as the coding of the "main stream" of the program. It is, as if, I say, writing the code is something like a drawing of a picture on the front side of the canvas. and the writing the exception handling part is like a drawing on "the back side of the canvas"!! You can't complete your art, until you complete the both side of the canvas.

    • @IAmTimCorey
      @IAmTimCorey  4 года назад

      Interesting way of looking at things.

    • @edwardmullan2724
      @edwardmullan2724 4 года назад +3

      I would say it's like wiring a house, you need to put fuses and circuit breakers in so the whole thing doesn't burn down when you fire up you faulty toaster

  • @RealJustinEstrada
    @RealJustinEstrada 4 года назад +2

    best and most complete explanation on youtube, thank you sir.

  • @ramonchitobendijo3465
    @ramonchitobendijo3465 3 года назад +3

    Actually, you can remove the catch in the GrandParentMethod and it will still be caught by the UI (Main method which calls the GrandParentMethod). I also want to point out that the catch in the grandparent method is called even before calling finally. The catch method however in the UI is called after the finally block hence the reason why you can see that DB connection is closed before Console.Writeline in the UI is shown.

  • @vijeshkanth4604
    @vijeshkanth4604 4 года назад +1

    Hi Tim, it's been great to watch out your videos for learning any C# basics and advance topics. You make the things so better and understandable.It's important to realise how to write a proper code, I am glad to you for that. Can you please make a video on File Operations also. Thanks in advance.

    • @IAmTimCorey
      @IAmTimCorey  4 года назад +1

      I will add it to the list. Thanks for the suggestion.

  • @nc3768
    @nc3768 3 года назад

    I dont comment on videos but i had to write a comment after watching it today for the second time just to fully comprehend. Love your detailed explanation and love the video tags as well: it helps when coming back. Recap is the best part of this video after watching it in the past but you want the 2 minutes explanation.

  • @marcocambon
    @marcocambon 4 года назад +2

    Hi Tim, nice and clear explanation that immediatly highlights the main common mistakes. Also very clear english even for an italian :)

  • @goodmanshawnhuang
    @goodmanshawnhuang 2 года назад +1

    Thanks a lot Tim, I often eat exceptions and will stop doing that 😂. really love the way you explained it.

  • @Barrosy
    @Barrosy 2 года назад +1

    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.

    • @fadidib8516
      @fadidib8516 2 года назад

      wothout exception handling how is it even possible to fail gracefully does not make any sense

  • @michaelblair5146
    @michaelblair5146 3 года назад +2

    If anyone is wondering at 8:11 why their code isn't allowing them to access the Reference Library as a possible 5th option, That is because you forgot to add 'Public' access modifier to the DemoCode Exceptions Library project class.

  • @BijouBakson
    @BijouBakson 2 года назад +1

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

  • @karthiku1153
    @karthiku1153 3 года назад

    Thanks Tim. This gave a clear picture on how to handle exceptions and helped me to address code review comments today. Really a good one and can't wait to watch other videos.

    • @IAmTimCorey
      @IAmTimCorey  3 года назад +1

      Glad it was helpful! Plenty of other videos posted out there. Please let me know what you think of them also.

  • @DivakarRaj
    @DivakarRaj 3 года назад +1

    Amazing amazing video. Showed how elegant exception handling is !!!

  • @amortalbeing
    @amortalbeing 2 года назад +2

    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.

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +4

      Exceptions can be expensive but broken applications can be even more expensive. I did mention that exceptions are expensive in this video, but there is a balance here. I'm not prepared to say that the best thing is to avoid them. Throwing an exception is the right thing more often than that. Otherwise, you introduce potential vulnerabilities into your application.

    • @amortalbeing
      @amortalbeing 2 года назад +2

      @@IAmTimCorey I guess I didn't convey myself well, I as well do not mean not to ever use them.
      When I said one should strive to not use exceptions as much as possible, was to proactively be wary of situations that can result in an exception and prevent them as apposed to let it happen and manage it in an exception handler.
      For example, instead of accepting all forms of an input and then resorting to a try catch instead of proper validation is clear example of such misuse that I was trying to ward off.
      I guess, I'd call this kind of exception handling, sweeping one's irresponsibility/laziness under the rug.

    • @BijouBakson
      @BijouBakson 2 года назад

      @@amortalbeing I believe preventing the user from entering bad data is subject to training or familiarity with the system. You cannot guarantee that all your users are properly trained, especially if you're dealing with an application that is available on the internet. If you mean entering a code that only allows the user to enter some type of data, that is literally error handling. Maybe you were referring to using other methods that try-catch?

  • @user-pz1cd8lv3n
    @user-pz1cd8lv3n 10 месяцев назад +1

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

  • @Jose67898
    @Jose67898 2 года назад +1

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

  • @shaileshaggarwal8802
    @shaileshaggarwal8802 5 лет назад

    OMG! I have been a developer for quite sometime now. But definitely did not know most of the basic you just described... Hands Down!!! Great video! I always learn something new from your videos.

  • @guntbert9709
    @guntbert9709 6 лет назад +1

    Thank you Tim, again. A very nice introduction to exceptions - amazing how you pack all that into not quite an hour!
    Allow me just one remark: you don't need `catch` when you just want `finally`, there exists even a snippet `tryf`.

    • @IAmTimCorey
      @IAmTimCorey  6 лет назад +1

      Thanks for the tip. I should have pointed that out. I wanted to highlight that you could do logging, etc. in your catch but I forgot to mention you could skip the catch if you just wanted the finally. Good catch (see what I did there?)

  • @elikescode5753
    @elikescode5753 6 лет назад

    I love when Tim says "Allz it doez". Keep up the good work.

  • @tinobickel
    @tinobickel 5 лет назад

    Hey Tim. Great Video series. Instead of looping through all InnerExceptions you can simply call ex.ToString(). It already returns "message" and all InnerExceptions.

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      Yep. The only downside is that you have to slog through a bunch of text then.

  • @facundovega1726
    @facundovega1726 3 года назад +1

    Amazing content as always. thanks for sharing all your knowledges Tim!. Regards from Argentina.

  • @mikemac7408
    @mikemac7408 3 года назад +1

    Little tip for those interested. Xamarin Workbooks is great for learning APIs and practicing concepts in isolation. You can write nicely formatted markdown alongside your code to document and explain your reasoning process. You can then save and share your work in a single, self contained file.

  • @jeremiahmedel9608
    @jeremiahmedel9608 3 года назад +7

    We can't fix users, wish we could -Tim Corey

  • @LuisEduardoHernandezT
    @LuisEduardoHernandezT 5 лет назад +1

    Instant like & subscribe! So simple explained. Basic stuff, yet how common it is to use exceptions the wrong way.

  • @SpesEtFides111
    @SpesEtFides111 6 лет назад

    Very good as always. Thanks for all you do to help others, Tim!!

  • @roquefigueroa4916
    @roquefigueroa4916 6 лет назад

    Thank you for creating this video. This helped me understand exceptions a lot better.

  • @CantChooseNic
    @CantChooseNic 6 лет назад +1

    Thank you for making these practical videos!

  • @Ruslakall
    @Ruslakall 4 года назад

    Worth mentioning that you only get the "in" part of the exception stacktrace if you are debugging and have the .pdb file with the executable. I've actually copied the .pdb files by mistake into production environment and later seen a reference to my local machine in a logged exception :)

  • @AliMustafa-xp8ih
    @AliMustafa-xp8ih 9 месяцев назад +1

    what a great tutorial , Thank you TIm

  • @amineayoubiIT
    @amineayoubiIT 5 лет назад +1

    Best explanation ever seen , keep going sir .

  • @ernstpeterlegrand
    @ernstpeterlegrand 4 года назад

    Thanks again, gives me for sure a better understanding of exceptions.

    • @IAmTimCorey
      @IAmTimCorey  4 года назад

      You are most welcome. Thanks for watching.

  • @arpitajoshi190
    @arpitajoshi190 2 года назад +1

    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

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +3

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

    • @arpitajoshi190
      @arpitajoshi190 2 года назад

      Done. Thank you!

  • @shrirangpinjarkar
    @shrirangpinjarkar 4 года назад

    Thanks a lot man. Very well explained best practices for exception handling.

  • @sheznabiel985
    @sheznabiel985 4 года назад +1

    Great video, good pace and easy to follow! Subbed! Thanks

  • @karimmessaoud8223
    @karimmessaoud8223 2 года назад +1

    Very good explanation. Thank you.

  • @trustingod0
    @trustingod0 2 года назад +2

    @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 !!!!

    • @DMC428
      @DMC428 2 года назад +1

      Obviously I'm not Tim Corey but may be my input can satisfy your desire to know more.
      Try-Catch-Blocks are used everywhere where an exception NOT ONLY lead to a crash but also to unexpected behavior. Your example sounds like the
      using (string ConnectionString = new GetConnectionString()) {
      ...
      }
      Bubbling up:
      You have a call-hierachy. Your Main-App calls a method, which calls a method and so on. Bubbling up means, you pass information (in above case the "Exception"-Object) to the calling method.
      Example:
      Method "GenerateCarMesh()" calls "GenerateWheel()" which is calling "GenerateTire()".
      "GenerateTire()" throws an Exeption because some DLL or whatever was not found. When you bubble up the Exception-Object, you re-throw it, so your GenerateWheel()-Method will catch it again and so on.
      Hope this helps. otherwise you may watch the video again, because he explains it pretty good.

    • @trustingod0
      @trustingod0 2 года назад

      @@DMC428 Thanks for your help. I agree with some of the comments when they state that in this specific scenario it would not be appropriate to use a try catch block but i understand that to have a simplified case of illustrating how it works this waa suitable. In this particular case you should handle the error defensively. I try to only use it when i dont have any control over what might occur.

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +8

      It sounds like you are confusing exception handling and using statements. Using statements are used to ensure that we properly dispose of certain items, most notably items outside of our control such as database connections, file locks, etc. That way, we don't leave connections open or resources locked if our application fails. Exception handling (the try/catch block) is used to properly handle any unexpected event. For instance, trying to open a file that does not exist will throw an exception. Trying to access an array position that does not exist will throw an exception. Trying to connect to a database that refuses your connection will throw an exception. These exceptions need to be properly handled, or your application will crash in an ungraceful manner. There are also times when we intentionally throw an exception. The most common case is when we are writing a class library and we do not have control of who will call the library. We need to throw an exception if something unexpected happens.
      Bubbling up is the process that exceptions go through. Let's say you have three methods. Method1 calls Method2. Inside Method2, it calls Method3. Now let's say something unexpected happens in Method3. You can catch the exception right there and process it. However, it might require user interaction, or you might not know what to do with that exception inside of Method3. In that case, you would not catch the exception. If there was no exception handler in Method3, the exception would "bubble up" the call tree. Since Method2 called Method3, the exception would next look there for an exception handler. If it did not find one, it would go up one more step to Method1. Same deal. If there is no exception handler there, you get what is called an unhandled exception. That's an exception that crashed your application because your application did not know how to proceed.

    • @trustingod0
      @trustingod0 2 года назад +3

      @@IAmTimCorey Thanks for clarifying things.

  • @a.porteghali7402
    @a.porteghali7402 3 года назад

    When I started coding with C++ as a student about 1998 and then as an amateur programmer, I've realized in different circumstances that I was being somehow over obsessed by a misunderstanding of Object-Oriented concept. Honestly, I was used to applying Try-Catch only inside the objects, as I'd believed it is what exactly an OO programming says. Then, as a result, there were lots of Try-Catch blocks in the code, and I always was thinking to what extend this technique is enough? Shall I put this block in any part of code that there is a possibility of firing an exception? Now, it's clear to me, it was just another misunderstanding.
    Many thanks to you, Tim. Not only I learned something new, but, it formed a new mind set about handling exceptions in C++ and C# and correct me for another misconception of OOP.

    • @IAmTimCorey
      @IAmTimCorey  3 года назад

      I'm impressed at your willingness to learn and adopt. I am sure you are a great programmer.

    • @a.porteghali7402
      @a.porteghali7402 3 года назад +1

      @@IAmTimCorey Thank you! I really appreciate the time and effort you put into comments.

    • @michaelschneider603
      @michaelschneider603 2 года назад

      I also started C++ programming around that time and remember the confusion about exceptions, by myself and others. They were a relatively new or at least little known concept back then. Most people were used to C-style error handling, where functions/methods would return an int value telling either 0 for success or an error code. One didn't have a choice but had to check for errors and handle them right where they occurred. I remember functions being made up of sequences of if statements of the form "if (functionXSZ(...) < 0) { handle error; return errorcode; }". And the calling function one level higher had to do the same for this function again. When such a practice is the norm, it's no wonder when one gets worried about the idea to "simply let exceptions bubble up the call stack". :-)

  • @mateuszryszkaniec7345
    @mateuszryszkaniec7345 4 года назад +1

    Hi Tim, you mentioned about calling method from different environment like MVC or WPF etc (not having console) - I was hoping here you will recommend to use a "response" & "request" messaging classes where response base contains (bool IsSuccesffull, string Message) :)

    • @IAmTimCorey
      @IAmTimCorey  4 года назад +2

      I don't typically use something like that. Instead, I use ILogger for logging messages and exception messages for responses sent up the chain.

  • @ghevisartor6005
    @ghevisartor6005 2 года назад +1

    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.

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +3

      I'm not sure I see the issue with Blazor not having controllers. It really shouldn't change the way you approach things. If you want to crash your application on an exception, you can still do that. It sounds like maybe you are putting your logic in your controllers normally and are trying to figure out how to do that in Blazor. Instead of doing that, move your logic out of your controllers. Your controllers should do very little. If you take that approach, you will do the same thing in both. The code for a controller is practically the same as what you will have in a Blazor component.

    • @trustingod0
      @trustingod0 2 года назад

      Best practice would be that before an uodate that you make sure that the user exists first.

  • @fcu423
    @fcu423 5 лет назад

    Tim your videos are extremely great!
    Thank you and keep it up!

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +1

      Excellent! I'm glad you are enjoying them.

  • @goji5887
    @goji5887 6 лет назад

    Definitely one of the most useful videos, thank you very much!

    • @IAmTimCorey
      @IAmTimCorey  6 лет назад +1

      I am glad you think so. Thank you.

  • @jacanaro5735
    @jacanaro5735 Год назад +2

    exactly what i needed

  • @rodcka
    @rodcka 3 года назад +2

    Great explanation, Tim! I am wondering where should I put my custom exceptions when I'm working in a layered solution. Should they belong to the business layer (since they are related to the business rules), or should they belong to the presentation layer (razor, api etc) since they could be caught near the UI?

  • @goverdhanjayaram3683
    @goverdhanjayaram3683 7 месяцев назад

    Thank you very much Tim! Very well explained!

  • @vinuhosanagar1
    @vinuhosanagar1 6 лет назад

    Thank you so much Sir. You are always the BEST

  • @PaulMcKillop
    @PaulMcKillop 6 лет назад

    Another really good video, Tim. Many thanks.

  • @johng5295
    @johng5295 Год назад +2

    Thanks in a million.

  • @amaice
    @amaice 3 года назад +11

    tim

  • @dougwarner59
    @dougwarner59 3 года назад

    This was a fantastic video; I say this because I just learned about exception handling and it helped me better understand how to use them correctly. This video would have been too confusing (for me) if I knew very little or nothing about exception handling. It's kind of strange hearing you explain about arrays and the concepts of in or out of scope in such an advanced topic as exceptions handling. At this point in learning C# (which too me is a hard language to learn) you would think everyone would have a grasp on these basic concepts?
    I am assuming the index out of range exception you are using is only an example and is not one you would use in actual coding, because you could easily just check for this error against the arrays Length property and handle it without having to use the time consuming try/catch/finally statements.

  • @hihistorystory
    @hihistorystory 3 года назад

    Hi Mr. Tim Corey. This is your first video I watch and I feel it's really great. I start to understand the usage of try catch. I'm a c# beginner and I still have queries. As you said we aren't putting try catch block every where. We usually put try catch at somewhere we think there may be trouble or issue arise with unexpected user behavior. My question is, if we knew there would be a problem somewhere, what's the different between we put try catch and we do some checking? For your example, you use try catch to capture the exception while user put in demo.GrandParentMethod(4) which the argument is out of the index range. If we knew that there could be bad user providing input that's out of range, we can do something like if (position >= numbers.length -1) { // do something in U.I. to notice user about wrong input }. In this case it's not necessarily to use try catch right?
    Thanks for your great job. I will go on to watch all your videos that I need, and followed your podcast in Spotify too. Hope I will be a great developer as you some day.

    • @IAmTimCorey
      @IAmTimCorey  3 года назад

      Great question. Depending on the circumstances, identifying the potential problems and checking for them can be a great option. However, sometimes an exception is the right call because the application should not continue as if everything is normal. Take a method called IsOver18() for example. Maybe it checks the value of a file on disk to see if the person in that file is over 18. What value should it return if the file does not exist? Normally, it would return true for 18 or older and false for under 18. If the file does not exist, neither of these apply. If it forced one of the choices, we might make decisions based upon that information, which would be incorrect. That is why exceptions exist - the application should not continue as if everything is ok. That's why you would need to catch the exception if you were calling this method. Whenever the application gets in an unexpected state, an exception should probably be thrown. We don't always have the ability to pre-validate the data.

    • @hihistorystory
      @hihistorystory 3 года назад

      @@IAmTimCorey Thank you very much Tim. I'm going to attend some of your lesson in your website. I really need to consolidate my foundation for a long journey on c#.

  • @wafaza7934
    @wafaza7934 2 года назад +1

    thanks, bro your explanation is excellent

  • @Greebstreebling
    @Greebstreebling 2 года назад

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

  • @dypcio3687
    @dypcio3687 5 лет назад

    It's a very helpful video. Thank you Tim !!

  • @bahrian4394
    @bahrian4394 3 года назад +1

    if you had easy paisa integrations I would gladly donate on your site. I always find quality stuff on your channel that most people would give as paid content which's great. Thank you very much.

    • @tomthelestaff-iamtimcorey7597
      @tomthelestaff-iamtimcorey7597 3 года назад

      Interesting comments. You "always" get 'quality stuff' from Tim that is equivalent to 'paid content' from others, yet you would only contribute if he covers that one specific topic. Why is only that one topic worth contributing for while all the other 'quality stuff' is not? I'm just curious...

    • @bahrian4394
      @bahrian4394 3 года назад +1

      @@tomthelestaff-iamtimcorey7597 I think you got me wrong, easyPaisa is a payment method supported in Pakisatan. lets say CreditCards are not as commonly used as in your country. only was suggesting that if you had a payment method on your site that allows me comfortably do a small donation I would pay for it.

    • @bahrian4394
      @bahrian4394 3 года назад

      consiering buying monthly subscription is a bit too much for me.

    • @tomthelestaff-iamtimcorey7597
      @tomthelestaff-iamtimcorey7597 3 года назад

      @@bahrian4394 My apologies. I did an internet search before responding and saw the specific integration. It really thru me for a curve as to how limited that integration effort was... my bad! I understand now and GREATLY appreciate your statement. Sadly, I don't see that integration happening any time soon.

  • @fiddler-dv4or
    @fiddler-dv4or 4 года назад

    Another great tut, Tim. Thank you! I did not think to loop through exceptions looking at inner exceptions. great tip. Have you done an advanced exception handling video? For MVC apps specifically? Love to see your take on that also.

    • @IAmTimCorey
      @IAmTimCorey  4 года назад +2

      I haven't but I can add that to the suggestion list.

  • @harag9
    @harag9 6 лет назад

    Excellent & clear tutorial, thanks Tim. Will you be doing a more advanced lesson for Exception Pattern Matching in C#7?

    • @IAmTimCorey
      @IAmTimCorey  6 лет назад

      That's a firm maybe. I love the new feature and it would make a good little video. I'm just not sure when I'll fit it in. I did mention pattern matching in my Top Five C# 7.0 Features video but not specifically as it relates to exceptions I don't believe.

  • @papillonx101
    @papillonx101 5 лет назад +1

    Superior explenation, as always.

  • @shah10955
    @shah10955 6 лет назад

    Great video. Thanks. Perhaps a little discussion could be included on what happens when UI calls a service via Web Api etc.

    • @IAmTimCorey
      @IAmTimCorey  6 лет назад

      In what way? Like what happens if the call fails? Or if the API throws an exception?

    • @shah10955
      @shah10955 6 лет назад

      If the api throws exception.

  • @byolock6244
    @byolock6244 2 года назад +2

    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.

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +3

      Make the "Add User to Group" line a method that you call 10 times. Have it wrap the call inside the method in a try/catch. Have it return a status (success/failure). Basically, you are wrapping all 10 lines in a try/catch but doing it efficiently. A more efficient method would be if you can anticipate and avoid the exception but still let the user know of the failure. For example, if the group not existing is what causes the exception, get the list of all groups and check the list before trying to add the user.

  • @simonbaxter8001
    @simonbaxter8001 2 года назад +7

    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!

    • @Scion141
      @Scion141 2 года назад +3

      You're right, and I haven't even been coding for 5 years. It's all about data validation. Although, I think he was doing this just to introduce Exception Handling.

    • @trustingod0
      @trustingod0 2 года назад +2

      I love that. Defensive coding. But you have to keep in mind that you may be writing client code that accesses code that you didnt write which is the whole purpose of gracefully handling exceptions that you have no control over; For example if the server goes down. A lot of times as programmers we fail to see the big picture and thats where the expertise of Tim Corey comes to our rescue :) I would recommend watching the video again.

  • @davidramirez3322
    @davidramirez3322 4 года назад

    Thnks so much Tim !! a great video as usual!!

  • @mukunan6171
    @mukunan6171 5 лет назад

    I really appreciate for your explanation!

  • @gavingreenhorn
    @gavingreenhorn 4 года назад

    Very lucid and comprehensive video, only i don't think i get 'the why' of creating a new exception in that case. If it is just to prepend an error with user-friendly message, it looks to me that it would be easier and less wordy to do that via a separate Console.WriteLine() in that catch {} block.

    • @IAmTimCorey
      @IAmTimCorey  4 года назад

      Not every UI has a Console to write to. By throwing an exception with a better message, you allow the UI the choice of how to handle it.

    • @gavingreenhorn
      @gavingreenhorn 4 года назад

      @@IAmTimCorey Indeed, and you said so in the video... now i feel stupid. :) Thanks for your reply!

    • @vitorbacelar3729
      @vitorbacelar3729 4 года назад +1

      ​@@gavingreenhorn There is no dumb question, if it wasn't you the one to ask, probably would have been another

  • @mohammadranjbaran1897
    @mohammadranjbaran1897 2 года назад

    Thank you very much Tim.

  • @mihowbogucki4928
    @mihowbogucki4928 5 лет назад

    Thank Tim! Love your videos

  • @octavian9168
    @octavian9168 2 года назад +2

    Thanks!

  • @michaelvenero1509
    @michaelvenero1509 2 года назад +1

    Great video thank you.

  • @TraxxStudios
    @TraxxStudios 6 лет назад

    31:55 you can just use try finally if you don't need to do anything in catch (other than just throw).

    • @IAmTimCorey
      @IAmTimCorey  6 лет назад

      Yep, thanks. I should have clarified that.

  • @swapnilpakolu4395
    @swapnilpakolu4395 Год назад

    Thanks for great explanation!!

  • @gonmigamez9072
    @gonmigamez9072 4 года назад +1

    yooooooooooooooooo you are amazing dude
    you literally made my life easier
    you are actually my favorite

  • @Jose67898
    @Jose67898 2 года назад +2

    Köszönjük!

  • @duke227
    @duke227 6 лет назад

    Hi Tim, great video as always. Would be great to have a video that adds on handling exceptions when using async programming as well as maybe using events to get ui to display progress and exceptions. Does try catch return path work across async when method is running on a different thread than UI?

    • @IAmTimCorey
      @IAmTimCorey  6 лет назад

      Handling exceptions in async is mostly straightforward. You simply wrap the top level async call in a try catch and it will capture the exception on the correct thread. The two things you need to ensure (which you should anyway) are that the async call returns a Task (not void) and that you await the results.

  • @MM-vr8rj
    @MM-vr8rj 5 лет назад +21

    Plot twist: the title is a pokemon reference

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +1

      Sorry, I don't get it (not a pokemon fan).

    • @sasukesarutobi3862
      @sasukesarutobi3862 4 года назад

      @@IAmTimCorey The joke is that the main point of Pokémon is catching them, so this title would work just as well on a video about Pokémon.

    • @Strrroke
      @Strrroke 3 года назад +1

      @@IAmTimCorey turns out there is a term "Pokemón Exception Handling" which implies bad practice for exception handling:
      try
      {
      DoSomething();
      }
      catch
      {
      // do nothing
      }
      Pokèmon's motto is "Gotta catch'em all", hahah I've never heard about it myself, but it's actually hilarious.

  • @lauriedickinson5373
    @lauriedickinson5373 3 года назад

    Very helpful video! BIggest bit of new info for me is difference between throw; and throw ex; Thanks!

  • @dyachenkoserj
    @dyachenkoserj 5 лет назад

    Another great video. Thanks!

  • @ninasaabiyeh926
    @ninasaabiyeh926 Год назад +1

    If I have a code block which first reads a file from the file system then calls an API which takes that file as a parameter, both operations may throw an exception. What is the best practice here? is it to surround the entire code block with a try catch (multiple catch statements: catch IO exceptions then catch for other possible types) ? or to surround the IO operation with a try catch and surround the HttpClient code with a separate try catch ?

  • @mggray1971
    @mggray1971 3 года назад

    Hi Tim. Thanks for the Video this has helped a great deal in where to consider for utlising try/catch blocks. I have a further query which relates to the different types of exception filters that are available from the Exceptions class library. When you are designing code what makes you choose specific exceptions filters over the generic exception library. If this generic filter provides you with the correct error output why would you need to choose specific filters. I can see you have used the ArgumentException but this you threw yourself. Why and how would I use specific filters in code when you may be unsure as to what error could be generated by the code. Thanks in advance Mike

  • @Brokdarify
    @Brokdarify 6 лет назад

    Very nice explanation!

  • @ChiefsFanInSC
    @ChiefsFanInSC Год назад +1

    This is a great video!

  • @kostasgkoutis8534
    @kostasgkoutis8534 3 года назад +1

    What about throwing exceptions in constructors as means to validate arguments? Is this something you would recommend?

  • @zvone9035
    @zvone9035 5 лет назад +1

    Thank you very much :D