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

แชร์
ฝัง
  • เผยแพร่เมื่อ 1 ม.ค. 2025

ความคิดเห็น • 440

  • @haozheng8400
    @haozheng8400 2 ปีที่แล้ว +4

    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 ปีที่แล้ว +2

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

  • @knockedgoose4206
    @knockedgoose4206 2 ปีที่แล้ว +6

    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 ปีที่แล้ว +2

      I am glad my content has been so helpful.

  • @sanityinaseaofmadness7353
    @sanityinaseaofmadness7353 4 ปีที่แล้ว +4

    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.

  • @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 ;)

  • @Tarodev
    @Tarodev ปีที่แล้ว +5

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

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน +2

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

  • @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.

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

  • @stani1k
    @stani1k 3 ปีที่แล้ว +3

    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!

  • @roadtoalaska-fuerzaucrania3549
    @roadtoalaska-fuerzaucrania3549 3 ปีที่แล้ว +4

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

  • @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.

  • @buskilamaor9587
    @buskilamaor9587 4 ปีที่แล้ว +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.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      I am glad it was helpful.

  • @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.

  • @interiorecology
    @interiorecology 2 ปีที่แล้ว +5

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

  • @octavianbreazu8486
    @octavianbreazu8486 2 ปีที่แล้ว +2

    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.

  • @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"

  • @Jose67898
    @Jose67898 3 ปีที่แล้ว +2

    Köszönjük!

  • @AlejandroHernandez-ru1zz
    @AlejandroHernandez-ru1zz ปีที่แล้ว

    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.

  • @bb579774
    @bb579774 4 ปีที่แล้ว +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!

  • @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.

  • @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.

    • @IAmTimCorey
      @IAmTimCorey  3 ปีที่แล้ว +1

      I am glad it was helpful.

  • @brianmoore9281
    @brianmoore9281 4 ปีที่แล้ว +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!

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +2

      Glad it was helpful!

  • @octavian9168
    @octavian9168 2 ปีที่แล้ว +2

    Thanks!

  • @techbrojoe
    @techbrojoe 2 ปีที่แล้ว +2

    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.

    • @IAmTimCorey
      @IAmTimCorey  2 ปีที่แล้ว +3

      Glad it was helpful!

  • @demps1bm1
    @demps1bm1 ปีที่แล้ว

    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!

  • @RealJustinEstrada
    @RealJustinEstrada 5 ปีที่แล้ว +2

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

  • @marcocambon
    @marcocambon 4 ปีที่แล้ว +3

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

  • @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.

  • @karthiku1153
    @karthiku1153 4 ปีที่แล้ว

    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  4 ปีที่แล้ว +1

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

  • @dadpool21
    @dadpool21 3 ปีที่แล้ว +2

    Thanks

  • @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.

  • @Barrosy
    @Barrosy 3 ปีที่แล้ว +2

    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

  • @BijouBakson
    @BijouBakson 3 ปีที่แล้ว +1

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

  • @elikescode5753
    @elikescode5753 6 ปีที่แล้ว

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

    • @IAmTimCorey
      @IAmTimCorey  6 ปีที่แล้ว +1

      lol, I'm glad you enjoyed it.

  • @Jose67898
    @Jose67898 3 ปีที่แล้ว +2

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

  • @DivakarRaj
    @DivakarRaj 4 ปีที่แล้ว +1

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

  • @fzhel-g7q
    @fzhel-g7q ปีที่แล้ว +2

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

  • @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.

  • @MusicToMyEar1005
    @MusicToMyEar1005 5 ปีที่แล้ว +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  5 ปีที่แล้ว

      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

  • @goodmanshawnhuang
    @goodmanshawnhuang 3 ปีที่แล้ว +1

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

  • @amortalbeing
    @amortalbeing 3 ปีที่แล้ว +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  3 ปีที่แล้ว +5

      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 3 ปีที่แล้ว +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 3 ปีที่แล้ว

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

  • @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?)

  • @ASML-Veldhoven
    @ASML-Veldhoven หลายเดือนก่อน +1

    This was extremely beneficial, thank you!

    • @IAmTimCorey
      @IAmTimCorey  หลายเดือนก่อน +2

      You are welcome.

  • @facundovega1726
    @facundovega1726 3 ปีที่แล้ว +1

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

  • @AliMustafa-xp8ih
    @AliMustafa-xp8ih ปีที่แล้ว +2

    what a great tutorial , Thank you TIm

  • @zoltanjanosjanosi2025
    @zoltanjanosjanosi2025 4 ปีที่แล้ว +1

    "If you don't know how to handle exception or if you do not expect an exception and know its okay, let the exception crash your application." 14:32

  • @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.

  • @charged7177
    @charged7177 27 วันที่ผ่านมา

    Is there a video that explains when to use exceptions for method parameters and when to use simple if statements? Also, who should check for null arguments, the method calling (in that way we have many if statements) or in the definitions (one check)? I think that a video explaining these nuances should be perfect!

  • @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 11 หลายเดือนก่อน +2

    Thank you very much Tim! Very well explained!

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน +1

      You are welcome.

  • @SpesEtFides111
    @SpesEtFides111 6 ปีที่แล้ว

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

  • @amineayoubiIT
    @amineayoubiIT 6 ปีที่แล้ว +1

    Best explanation ever seen , keep going sir .

  • @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.

  • @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 ปีที่แล้ว +4

      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.

  • @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.

  • @LuisEduardoHernandezT
    @LuisEduardoHernandezT 6 ปีที่แล้ว +1

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

    • @IAmTimCorey
      @IAmTimCorey  6 ปีที่แล้ว

      I'm glad you enjoyed it.

  • @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 ปีที่แล้ว +9

      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.

  • @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 :)

  • @ghevisartor6005
    @ghevisartor6005 3 ปีที่แล้ว +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  3 ปีที่แล้ว +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.

  • @kostasgkoutis8534
    @kostasgkoutis8534 4 ปีที่แล้ว +1

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

  • @roquefigueroa4916
    @roquefigueroa4916 6 ปีที่แล้ว

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

  • @karimmessaoud8223
    @karimmessaoud8223 2 ปีที่แล้ว +2

    Very good explanation. Thank you.

  • @gonmigamez9072
    @gonmigamez9072 5 ปีที่แล้ว +2

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

  • @AhmadElkhouly
    @AhmadElkhouly 2 ปีที่แล้ว +2

    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.

    • @IAmTimCorey
      @IAmTimCorey  2 ปีที่แล้ว +9

      Exceptions are only preventable as long as you fully control the input and have full access to the user. That isn't always the case. For instance, if you are writing a library, you don't have access to the user so you cannot tell them anything or ask them something. So, when you are asked to open a file that does not exist, what do you do? If you return "false" or some other message, you are trusting that the caller knows what that means and handles it appropriately. That's a danger because people can call something and ignore the return value. Since it "worked" (didn't crash), they expect it to be successful. That leaves your application in a vulnerable state. That's how application exploits are created. People intentionally put an application in an unexpected state through bad input. An exception ensures that the issue is either handled or that it crashes the application. The application cannot be put into an unknown or unexpected state because it crashes before that can happen. That ensures the safety of your data.

    • @AhmadElkhouly
      @AhmadElkhouly 2 ปีที่แล้ว +2

      @@IAmTimCorey Got it. Thank you Tim for your time.

  • @MM-vr8rj
    @MM-vr8rj 5 ปีที่แล้ว +21

    Plot twist: the title is a pokemon reference

    • @IAmTimCorey
      @IAmTimCorey  5 ปีที่แล้ว +2

      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.

  • @tinobickel
    @tinobickel 6 ปีที่แล้ว

    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  6 ปีที่แล้ว

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

  • @mikemac7408
    @mikemac7408 4 ปีที่แล้ว +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.

  • @CantChooseNic
    @CantChooseNic 6 ปีที่แล้ว +1

    Thank you for making these practical videos!

  • @mggray1971
    @mggray1971 4 ปีที่แล้ว

    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

  • @sheznabiel985
    @sheznabiel985 4 ปีที่แล้ว +1

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

  • @jeremiahmedel9608
    @jeremiahmedel9608 3 ปีที่แล้ว +7

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

  • @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 ?

  • @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 ปีที่แล้ว +4

      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!

  • @wafaza7934
    @wafaza7934 3 ปีที่แล้ว +2

    thanks, bro your explanation is excellent

  • @tiagosutter8821
    @tiagosutter8821 5 ปีที่แล้ว +1

    Amazing content! Thank you very much!
    I have a question:
    I have a Class Library for all my logic, and an another project for my GUI (windows forms). All my data access is in my Class Library, which references Npgsql.dll (for using PostgreSQL). What I wanted to be able to do is use multiple catch blocks for different things, the problem is that Exceptions like "database constraint violation" is defined in the Npgsql library, so I can't catch these exceptions in the GUI, unless I also add a reference to Npgsql.dll to the GUI project.
    Is that ok for the GUI project to have a reference to Npgsql? Or this is bad because the GUI has to "know" that Npgsql is being used for the database?
    If this is bad, what would be the best approach? Should I create my own exceptions inside my Class Library?

    • @IAmTimCorey
      @IAmTimCorey  5 ปีที่แล้ว +2

      It depends. If you really want that error and you don't mind locking your UI into using PostgreSQL, you can add the reference (not the end of the world). However, you could also wrap that exception with either a custom one or a standard one that you can catch in the front-end. I'm assuming there is data in the DB exceptions that you want to get out that you can't by catching it as a general Exception. Create your own and then your dependency on your class library is all you need.

  • @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.

  • @shrirangpinjarkar
    @shrirangpinjarkar 4 ปีที่แล้ว

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

  • @ernstpeterlegrand
    @ernstpeterlegrand 4 ปีที่แล้ว

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

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      You are most welcome. Thanks for watching.

  • @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.

  • @pranaymhatre9271
    @pranaymhatre9271 4 ปีที่แล้ว +1

    Hi tim,
    I am getting delay when i try to add reference to consoleUI.
    Is it a bug in visual studio?
    So cazn we do anything about it.

  • @jacanaro5735
    @jacanaro5735 2 ปีที่แล้ว +2

    exactly what i needed

  • @a.porteghali7402
    @a.porteghali7402 4 ปีที่แล้ว

    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  4 ปีที่แล้ว +1

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

    • @a.porteghali7402
      @a.porteghali7402 4 ปีที่แล้ว +1

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

    • @michaelschneider603
      @michaelschneider603 3 ปีที่แล้ว

      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". :-)

  • @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.

  • @hihistorystory
    @hihistorystory 4 ปีที่แล้ว

    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  4 ปีที่แล้ว

      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 4 ปีที่แล้ว

      @@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#.

  • @shawnmofid7131
    @shawnmofid7131 5 ปีที่แล้ว

    Thank you for the content. Re: your DataBase connection example, if an application crash happens which is similar to an exception, would not that cause the DB connection to terminate also? I realize that was just an example to say in the case of exception, the code immediately following would not run. Is it possible to share another example? If I am in fact correct about the DB connection closing. I am thinking GC would take care of it, if nothing points to the connection object.

    • @IAmTimCorey
      @IAmTimCorey  5 ปีที่แล้ว +2

      If an application crashes and the database connection was not properly closed, the connection would stay open. The garbage collector (GC) only runs when the application is running. If you caught the exception but did not close the database connection, the only thing the GC would do would be to release the memory used by the class. It would not properly close the database connection. Think of a database connection as two people talking to each other in different rooms. If one person walks away from the conversation unexpectedly, that doesn't mean the other person stops listening. They continue to listen (and maybe even talk). To properly end the conversation, one person needs to tell the other person they are done so that the other person can walk away as well.

  • @viajeromero
    @viajeromero 4 ปีที่แล้ว

    Great video, thank you so much.
    I have a web API backend application, and I'm catching the exceptions in a global way and logging the exceptions and stack trace in a local file, also returning a 500 error saying "Something went wrong", we don't want to show what was the problem to the final user in production. Do you think that I also need to use try-catch in my controllers? I understand your point that we can customize our exceptions in specific places, but which situation would be useful to have it in? For example, business validations? Thank you for your unconditional help!

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      Remember that exception handling slows down performance. Doing it globally means the biggest performance hit. You want to handle certain errors in a specific way (file not found exception might mean you should wait for the write to be finished and retry, etc.) You also might want to tell the users something more specific.

    • @viajeromero
      @viajeromero 3 ปีที่แล้ว

      @Soy Orbison Hi, yes that's why I asked if it would be usefull for business validations, like you said, no parameter supplied or when the user doesn't fulfil any rule. I personaly use exceptions to return Error messages from my validations, I don't know if it's the best approach but it works fine in my current projects. Do you use NotFound for when you don't find any record? I always return succeded(200) in that case, coz I consider NotFound usable for when the user write a wrong url/api endpoint.

  • @ramonchitobendijo3465
    @ramonchitobendijo3465 3 ปีที่แล้ว

    Just want to ask though, what did we do with the inner variable we used in while? Is it unused variable?

  • @PaulMcKillop
    @PaulMcKillop 6 ปีที่แล้ว

    Another really good video, Tim. Many thanks.

    • @IAmTimCorey
      @IAmTimCorey  6 ปีที่แล้ว

      I am glad you enjoyed it.

  • @kothapallirajesh7994
    @kothapallirajesh7994 9 หลายเดือนก่อน +1

    Hi Tim, why finally block was not executed, while getting exception in catch block that is present under Main method.
    static void Main(){
    try{
    // getting exception here
    }
    catch(Exception ex){
    //again getting exception here
    }
    finally {
    // code
    }
    }

    • @IAmTimCorey
      @IAmTimCorey  9 หลายเดือนก่อน +1

      An exception in a catch block is an unhandled exception.

    • @kothapallirajesh7994
      @kothapallirajesh7994 9 หลายเดือนก่อน

      Thanks for your reply, but at any point of time finally block should always execute unless we use the system.exit(0), so even an unhandled exception occurs in the catch block but still needs to execute the final block. So why not in the above case?

    • @tuvantran660
      @tuvantran660 9 หลายเดือนก่อน +1

      @@kothapallirajesh7994 I think the finally block only executes in the following cases:
      1. Happy case try success
      2. Error happens in try some error events fire, catch block execute success
      and if and error happens in catch block, like Tim said where is the code block to catch and handles this ? - the program terminates and log error to the console.

  • @tanws8
    @tanws8 ปีที่แล้ว +1

    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.

    • @IAmTimCorey
      @IAmTimCorey  ปีที่แล้ว +4

      I don't. Your options are going to be either to catch every exception and handle it properly or let things go to an exception page. My recommendation is not to do a global exception handler. Instead, handle the exceptions that you think should happen and let everything else crash. Then, read the crash reports and figure out why the application crashed. Don't just hide the fact that it is crashing. Otherwise, you could put your application in danger of attack.

  • @papillonx101
    @papillonx101 6 ปีที่แล้ว +1

    Superior explenation, as always.

  • @krishpatil80
    @krishpatil80 4 ปีที่แล้ว

    Hi Tim, Thanks for an amazing video. Question - What is the benefits of global Execption handler(middleware) than decorating try catch on each method. what are the best practices . can you please throw some light on this. Thanks!!

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      A global exception handler ensures that the application does not fully crash, which seems like a good thing but often is not. An application should fail rather than continue in a bad state. Also, a global exception handler does not have the ability to interact with the information and potentially fix it. It is designed to be for logging mostly, not actually stopping the exception. A try/catch can process the error right there, adjust things if possible, and alert the user (since it has access to the UI piece that called the method typically).

    • @krishnatpatil2866
      @krishnatpatil2866 4 ปีที่แล้ว

      @@IAmTimCorey Thanks tim

  • @broski1491
    @broski1491 4 ปีที่แล้ว

    Hey Tim, for some reason my references don't show up on my solution explorer box, usually after creating a new library, i was once unable to finish your 24 hour project after being stuck at 6:01:00 where you usually add a reference from Assemblies, i also noticed that i don't see COM references there, also i tried to create a reference as you did using ctrl dot. It would just keep loading... hope it's not fault on my side, hoping to see you reply!
    PS: Really need help with fixing those references...

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      The first thing I would check is to see if you are mixing project types (.NET Framework and .NET Core), which can't talk to each other. If that isn't it, try repairing or re-installing Visual Studio.

    • @broski1491
      @broski1491 4 ปีที่แล้ว

      @@IAmTimCorey Hey Tim Corey, i appreaicate the reply, but just a question, how do i check if i'm mixing .NET Framework and .NET Core? Do i Open Visual Studio and search where i usually make a New Project?

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      In the solution, right click on the project and select Properties. It should tell you what project type it is in the first tab. Do that for each and make sure they are both either .NET Framework or both .NET Core.

    • @broski1491
      @broski1491 4 ปีที่แล้ว

      @@IAmTimCorey I rigght clicked on the solution name, then properties which appears at the bottom. I see Startup Project and there it says Single Project, Multiple Projects. Is that what you meant, sir?

    • @broski1491
      @broski1491 4 ปีที่แล้ว

      @@IAmTimCorey Hey Tim, i'm still confused about it, can you tell me if it's in the solution explorer in the project or if it's somewhere outside of my project.

  • @vinuhosanagar1
    @vinuhosanagar1 6 ปีที่แล้ว

    Thank you so much Sir. You are always the BEST

  • @Layarion
    @Layarion 6 ปีที่แล้ว

    20:00 i'm actually confused, wouldn't the exception have happened at line 27 instead of 28? because line 27 is when it tries to get an index that doesn't exist.

    • @IAmTimCorey
      @IAmTimCorey  6 ปีที่แล้ว +1

      No, line 28 is correct. Line 27 is just where we declare the array. On line 28, we are actually trying to access the array at a position that does not exist.

  • @davidramirez3322
    @davidramirez3322 5 ปีที่แล้ว

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

  • @Glip96
    @Glip96 4 ปีที่แล้ว

    hi Tim. i have been a fan of yours videos since 2 or 3 years ago. they have me view a larger (perhaps a wider) picture about developing in visual studio , .net, asp and c sharp. I have been programming since a long time ago in visual foxpro and i'm still maintain several projects.
    Mi question is: what is the best way to reuse code in csharp and where to put it. In my deveopment machine i have a folder with code, forms, reports, etc wich i constantly access in order to take some routine or some form or some visul class that i use in the most of my project. also, when i found a process that is suitable to become an asset in my portfolio of components, instead of doing it as a part of a solo project i add that code or form to my library. how do you think is the best way to do that in csharp/visual studio development environment?
    Thanks for yours videos and your help

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      If the code is the same all of the time, you could create a personal NuGet package with all of your reusable code. If the pattern is the same but the code might be a bit different, create a class library with your examples and then just copy and paste what you need. I do that a lot (or just retype it). It saves a lot of time over trying to memorize things and then forgetting one piece that then causes me to debug for hours.

  • @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.

  • @mihowbogucki4928
    @mihowbogucki4928 5 ปีที่แล้ว

    Thank Tim! Love your videos

  • @johng5295
    @johng5295 2 ปีที่แล้ว +2

    Thanks in a million.

  • @das_evoli
    @das_evoli 3 ปีที่แล้ว

    There is still one question I have:
    When should we bubble up an exception and when should we just use "return null" for example.
    Let's say we call GrandParentMehod() who should return an object. Is it enough to just return object null to the caller when an exception happens or should we bubble up the exception that happend and handle it in the caller.

    • @IAmTimCorey
      @IAmTimCorey  3 ปีที่แล้ว

      It will depend on the situation and how you build your software.

    • @ryanye6938
      @ryanye6938 3 ปีที่แล้ว

      @@IAmTimCorey if bubble all the way up, I think it's good to terminate the program or returns the message back to the user. right?