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

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
a lot of developers have an incorrect view on exceptions and how to handle them in this video we're gonna look at what exceptions are how you should handle them and probably most importantly where we should handle them my name is Tim Corey and it's my goal to make learning c-sharp easier if that seems like something that you would benefit from sign up for my mailing list the link is in the description below the very first thing will happen is you'll get an email from me that you can reply to let me know if you stroll with and what topics would best benefit you you'll also get discounts on courses that I offer alright so let's build a demo application that has a problem so you can see what an exception is and what it does here I have Visual Studio 2017 I had the Enterprise Edition but don't worry the same will work in the free version of Visual Studio 2017 Community Edition if you don't have that good of Visual Studio comm and download the community Community Edition you can also check out my video on the top 10 free tools that you can get because Visual Studio is one of those tools alright so go ahead and create a new project over here on the Left we have visual c-sharp windows classic desktop so I have selected and I'm going to choose first the console application and the reason I going to choose console application this is a pretty common one for me with demos and it seems kind of archaic but it's really not really actually powerful because a console application has very little setup work it just kind of is it just kind of runs and so I don't have to get a lot of time invested in creating a demo I'll encourage you as you learn new topics build a console application to test those topics out if you're not sure if you exactly know how things work build a console app try it out if you're going to put a new technology into your project at work build a console app first make sure you know how it works and make sure you've worked out the kinks in a application you can throw away don't start by testing in your actual application that's just a recipe for disaster okay so we're gonna call this console UI and this is going to be our exceptions demo the solution name once this gets created the first thing we do the console application is a very end and the console read line at the end and the reason for that is because we wanted to pause before it closes the application that we can read what's on the screen now before I go any further I'm going to do is actually add a class library as well let's go a solution we're gonna add a new project call it class library and this will be our exception library exceptions library and we the first we do is delete class one and then create a new class so right click and say add class and this is just standard setup stuff we're gonna call this our demo code alright so class demo code make it public what we're gonna do is I create a method here that is they could possibly fail and it's a really stupid methods don't think there's any kind of you know code that you'd really implement at some point but let's create a public int get number and we'll pass in a position all right and so we're gonna have is we're going to have an int array and typically I don't use arrays I use lists instead but this is just a little more clean this way so and Crean int array and call this numbers it's a equals new int and then we'll do a open and close curly brace and say one for seven and two so we've done here is we've initialized an array called numbers it has four items in it the items are one for seven and two and just remember that that arrays have a zero based counting system so this is position zero position 1 position 2 and position 3 so now we'll do is we will return the number so numbers at position position so all this method does is it has this array we pass in a position and it give us back that number so if I pass in position number two it's gonna say ok 0 1 2 it's going to pass back the value of 7 and that's pretty simple stuff so we we know that we pass in position in and we get back a value now those of you who are kind of more familiar race will immediately see the problem and that is what if I pass in position 10 well there isn't 10 positions here 0 through 9 there's we don't have that many we have 0 1 2 & 3 so position 10 would be out here somewhere and we don't have it so we're gonna get an exception it's gonna say hey that's out of bounce but I do want to add a couple of more calls to simulate what a real-world feel for this would be typically in the real world you wouldn't have your UI which is the console you wouldn't have that call the actual deep-down method and that'd be it usually you have a method that then would call a method which would call a method which would call another method okay because you have you know larger methods that call a whole bunch of smaller methods so we're gonna simulate that public int parent method will have same imposition and it's going to return get number and pass in the position so as parent method we call it all it does and again us as demo code is it calls get number and returns a value that number returns right call where I have one more method public int grandparent method and you probably guess what's gonna happen here return parent method position okay so grandparent method calls parent method which calls the get number which does the actual work that way we kind of simulate those layers so over here in our program CS we're going to add the reference now this is kind of cool I want to show you something if I were to say demo code I haven't added a reference in console to the exceptions library but if I type it out correctly then a control dot one of the options now the first for generate that means create new code for this we don't want to do that the last one here is add reference to exceptions library if I do that it added my reference right here to my library and to add a using statement up here for the exceptions library that's a newer feature of Visual Studio it's kind of it cuts down and the most steps we need to take the only trick here is you have to type this exactly right you can't have a lowercase C you can't have a lowercase D you can't have an extra uppercase it's gotta be exactly right so demo code arrests a demo equals new demo code with is an instantiated class it's no it's called demo dot call the grandparents we'll pass in the position of 503 which we know work and I'm going to assign this into result equals demo dot grandparent method and then we'll do a console.writeline where I say dollar sign couple double quotes we'll say the value and the given position is result and let's run this so they should all work in theory all right so the value of the given position is two may have look at our code zero one two three position three the value is too cool now this isn't this demo isn't about making things work right it's about making things fail you can blow up so let's do position for which we don't have one let's run this and this is what happens I get a system dot index out of range exception this is an exception what it means is I had a problem and I'm crashing so here is the exception information we can actually go the details here and get more information so there's more information about the exception but if I were hit continue the application stops and the reason it stops is because we had what's called an unhandled exception so if we were writing as application without the visual studio debugger attached what would have happened is it we're just crashed now since we had a debugger attached it actually pause the code and taught and show us the exception and show us where it was but if this was running in production somewhere the user wouldn't get that they would just get one of those nasty dialog boxes saying hey it is probably this application that problem and it's closing so we want to solve that problem now I'm gonna introduce something you've probably seen before especially if you watched any demos and that's the idea of try-catch now I'm gonna first put it around where we know the air exception is that's not the place I'm going to keep it but I want to at least show you what typically people will do when they learn about try-catch they say okay I know that this is a this is potentially a problem if you pass the wrong position in it blows up so what I'll do is I will wrap the entire thing in a try-catch so I hide the code say snip it surround with I type out try and tab okay so there's a try-catch now the first thing it does is it says okay there's an exception and you say well sure whatever and you say I don't want to throw it again so I'll do this let me just demonstrate what happens here first of all it says hey nope you can't do that because not all code paths return a value now some people might do this int output equals 0 and then say outputs equals numbers and then after the try-catch they'd say return output let's try this here's a code the value of the given position is 0 is that correct no it's not correct what happened well the try-catch protected us from blowing up there was no unhandled exception and this is where a lot of rookie programmers will go yeah I fixed the problem you didn't fix the problem you actually made it worse ok and here's why when you had this exception that's important to know because an exception is critical information you need know what it's saying is the way you expected your application to work it didn't work that way you need to know that because if you allow your application to continue when it's in this unexpected state you could do odd things you don't want odd things in your application think for a minute if you were an application that saved user information and the first step is save their first and last name to the database if that through an exception and you just hid it behind a try and just didn't do anything mix in a catch it would continue on as if it worked and then it would save the address information for a person with no first and last name that a bad data in a system just compounding itself so exceptions are there for a reason don't just say they're ok or hide them ok there's a reason why they stopped applications in fact and it's something that I have a hard time getting my head around the if you don't know how to handle exception or if you don't expect an exception and no it's ok let the exception crash your application it's better that it crashes your application then you continue in that bad state or unknown State so in essence it's sometimes better your application crashes horribly rather than continuing now I want to show you how to lie your application to continue in some circumstances because there are a lot of times when an exception may happen but it's not the end of the world say for example we're saving that user an exception happens on say the first and last name we could stop it the process of saving their data but not kill the application may apollo box up us says hey i couldn't save his person and there may be a you know a try again button they can try again may it works or a try again doesn't work they could send a note off to the IT department to fix the application but they can still use the rest of it so as ways ways we can catch these exceptions and do something about them but we have to be careful don't just eat exceptions this is eating an exception not doing anything about it here now we could say exception e X and so this catch is doing right now is saying I'm gonna catch every exception I'm gonna put that exception into this e^x variable now we can do this is we can actually get more information about what happened for example e^x dot message this will tell us what happened that caused this to fail now let's run this and I'll show you a better way next so here we get this message right here index was outside the bounds of the array that's our e^x top message now notice since we didn't do anything else to catch finished and we still returned output so he didn't stop the application from running we just put out a message saying here is a problem but we can we've kept going not the best solution so we rethink that but also there's a whole lot more information about the exception than what message it gives us so don't just give the user the message you got to do more of this in order to help your developers or help yourself track down what the problem is let's put a breakpoint right here so we can see what all this e^x variable has all right so we hit the variable and now let's let's look at this and the font is small I'll actually capture more s data in the actual message but it's a whole bunch of other pieces of data in here that we can use let me show you let's stop this let me show you the piece of data that I find most useful console dot right right line there you go yes dot stack trace so what this is is it's where exactly the the exception happened so if we run this it says okay we have an index outside the bounds of the array that's our X dot message but then down here this is the stack trace at exception exceptions library demo code dot get number well that's this is the exceptions library is the project demo code is the class get number is the method and it's saying the get number is passing in the int 32 position because don't forget you can have an overload with multiple different calls to get number so as is a specific get number method and here's where it's located all right down to the demo code ciass file and that's the full path to it line 28 whereas line 28 right here so that's the offending line so as told us here is the CF file he's a full path notes you can get right to it if for whatever reason you had CS files all over your disk it also told us the the namespace and the class and the method so we could get right to as well and the line number so you can get right to the exact place where the problem lies line 128 and so that allows us to see okay we had an index outside the bounds the array that's a very specific message it says the index which is which I might erase that's the the number inside here the position the index was outside the bounds of the array meaning the bounds of the array are in this case is 0 to 3 it's a that's the spaces that are taken up in the array we called something outside of that now again it's still continuing on because we look up the message the value of the given position is zero because we never did anything with its exception except for log it so let's do something about this exception now this is where it gets a little tricky what do you do at this right now here well there's not hole we can do because we don't know if we can continue on or if we need to shut this whole application down and the reason we don't know if we don't know anything about the caller the original person the original bit of code that called what eventually became this method we don't know why it was called we don't know how important it is none of that information is down here at this level and that's why we don't put try caches down here instead and let's go ahead and for now I'll go ahead and comment out this try-catch so we're back to throwing the exception if we start this and run it it throws exception unhandled exception unhandled and if we continue it crashes the application instead let's go to our user interface which is our console application and in here this line of code we know this can be problematic so we right click on it say snippet surround with try it'll do the exception e^x and we're going to comment or take this line of code out and we'll say something like a X dot let's do the same thing the message and e^x dodds stacktrace I want to show you a difference now first of all we're gonna an error right here that says that the iota given position is and the result and that's because we declared the result inside the try and that's these career aces determine the scope and so anything declared inside these career aces does not live outside those curly braces therefore we need to move this line of code let's cut it out here and paste it in the Tri section which is good because then we'll either have an exception or get the value in fact let's make it a good value first so let's put they have two instead and if we run this we get this message the value given position is seven so that's good that means that it works when it it's supposed to we put four back in and we run this again we get this message index was outside of balance in the array but notices more information here now it line wraps it's a little bit hard to read because of that but let's look through this stack trace and this is where this is so valuable and why we want to put our try catches as high as possible it says the exception was at and it gives the the get number line twenty eight we're used to that but then at parent method line eighteen and at grandparent method line thirteen and finally at console UI and their location line eighteen what's line eighteen of console UI this line right here that's what the exception actually happens so why is that more valuable instead of just more clutter well we have this whole list here we can track through where we were calling so if you just have the get number you don't know who called that why they called it where they called it anything with the full stack we know oh is the console application that called the actually called the grandparent method I didn't call get number they call the grandparent method and in fact that grandparent method didn't even call get number it called the parent method and so we have us full history from the root call all the way through until the actual exception that gives us a lot of valuable information about how it was called not just that it was called so that's why I always encourage people let the exceptions happen at the lower levels and let them come up through until the top level or as high as you can go now there may be a case where you say yes but I actually want to capture it at say the grandparent method level that's fine say that you have you know the grandparent method is actually the the overall saved the database and it's gonna call a number of methods underneath that save different parts if there's an exception in one of them the grandparent method should know about it so it can do some cleanup and also kill the overall operation that makes sense to put it there but in general as high as you can go the higher the better the other reason why it's great to have it this high level is because if you're down here at the git number how can you tell the user what went on now I cheated okay this is a cheat right here because I knew that this class is being called my console application and really I even did some I price should have done which is call the console the UI from the class library it kind of crossed all those boundaries that's not something you should do in a normal class library because this might be called by a MVC application or a WPF application in that case they don't have the console so even though technically won't crash what it would do is it wouldn't show the user anything so that's not how you want it to work you want be able to tell the user I had a problem where do you tell the user anything the user interface that's the whole point is we only talk to the user in the user interface so that's why it makes sense to put your try caches at the very top level or at least somewhere in the user interface but the example of the grandparent method the man overall database call it makes sense that the grandparent method kind of process that exception and change how it responds because of that so how do you do that well let me show you let's pretend this grandparent method needs to act on exception in some way maybe needs to stop processing a more records maybe it needs to close out some a connection okay now normally use a using statement and if you watch my c-sharp a sequel video c-sharp application talking to sequel databases you'll see a using statement there but let's just pretend that we want to close out of a connection oops so we're going to do is making code modifications I'll just say int output equals zero and we'll say output equals the parent method position our parent method and then we'll return output so we're saying is that maybe you know here we're opening database connection and then here we're closing it so let's just pretend like we're doing that open database connection and then down here we'll close database connection okay now without doing anything else you know this is the the normal application where we open database connection we do stuff then they close that connection without changing anything else let's run this application okay so we have open database connection we have exception we have no closed database connection so we now have a database connection it's kind of hanging out there and that's not good especially if this exception happens a lot say we have 100 users and 95 of them get this exception well now we have 95 open connections to the database maybe every start and try it again so now we have you know a bunch more 190 app you know open connections definitely not good so this is where we would need a try-catch and this level so I can right click and say snippet surround with try and let's go ahead and grab for now I'll grab the exception e^x and the first going to do is going to show you how we can do we can close this connection no matter what so what I'm gonna do is say finally what happens with a try catch finally block is finally runs no matter what so it doesn't matter if you have an exception or not this codes gonna run now what that also means is you better not put code in here that might cause an exception because then you've got another problem you've actually got an unexceptionable so make sure that this is is good code but with a try catch finally this will run no matter what the problem is is that this is not the UI layer so we can't tell the person in here that there's a problem now again we're simulating we're calling console here even though it's not the UI layer that's just for demo purposes but here we're saying we can't talk to the UI because this is the wrong area for that we don't know how to talk to the UI you're the console we do console.writeline if it was a MVC application maybe we you know open a new controller we have you know some method of of bubbling up errors to the user so how we do this well we call throw and so what throw does is it says okay I'm gonna catch the exception but then I'm going to immediately pass it up the chain so it's is essentially saying I never caught in the first place and the reason we use this is it for a couple of reasons one I could do some kind of logging here so I could do some logging at this line and say log that exception but then pass up the user interface to actually display it to the user also it allows us to have as finally block which will allow us to do things like close our connection before we pass that exception up the chain so if nothing else being done we have open connection close connection and then we have the exception information because we open the connection here we did try and we ran this line it blew up so it comes down here the catch the catch does nothing but say throw it so it's gonna say hey I'm ignoring the fact that we had caught this exception I'm gonna throw it back and let the next item up the stack catch but before you do run the finally code that finite codes is okay close a database connection so it has a try it fails goes here it says throat again okay but first close a connection then throw it up the chain where the program dot CSV file catches it and give us our exception information so that's how exceptions work and that's how we bubble exceptions up wherever an exception happens say down the get number it looks to see if as a try-catch if there is the catch processes and does whatever it says if there's not it tells the caller who called it hey I have an exception the caller looks for a try-catch says nope I'll have one pass the exception up to who called me which in this case is the grandparent method the grandparent method says oh yep I I am inside a try-catch therefore go to catch this catch in particular says I'm not actually doing anything except throwing you back into the into the bubbled up pathway but I am saying go ahead and run my finally code first that gets run and it gets thrown back in to bubble up one more layer so is there so it says okay who called me well that's over here that's who called me is there a try-catch here yep there is therefore I'll hit my exception block and I'll do whatever you say and then we're done and since this catch didn't actually say throw again it stopped at this and it said okay we can continue on because the application is in a working state and that's we have to figure out is make sure that if you don't have some kind of throw in this catch that the application is okay to continue if it's not you may even want to say you know closed application or displaymessage and then closed application or something like that if it's that drastic so that's how bubbling up exceptions works it starts at wherever the exception is and it goes up the stack and a stack is the parent who called me the parent who called my parent the parent who called my parent so I just keeps going up the caller list looking for a catch block if it doesn't find one if we inhabit try-catch here it's called an unhandled exception and that blows your application up and shuts it down now one of the thoughts people have is can I have a global exception handler and the answer is yes but why because wherever an exception happens you need to do something with it and that's where the user interface comes into play so you want to display it to the user and you also need to make a decision about whether or not to continue your application does the global exception handler know about the calling procedure does it know why we called the method in the first place well know it's a global exception handler it handles all the exceptions so the global exception handler is not really the place that you want to have processing your exceptions you want to process your exceptions wherever it makes logical sense whether it's to tell the user that something happened or whether it's to stop and process something in order to shut down safely or to clear data out that was half-formed or whether it's just to say okay we know it's a problem but it's not a big problem I want to continue on so that's why try-catch is so often done poorly is because people don't understand what they're doing with a catch they're just thinking I am hiding or or fixing the application from crashing crashing is not your problem your problem is you're not properly dealing with issues that arise okay now let's talk through a couple of things that people get wrong when dealing with these exceptions and this let's just stay right here in the grandparent method so I just did throw that's it throw that's the proper way of put an exception back into the the bubble up process you might see this so we have the exception object let's go ahead and throw it again so you'd think these two just throw or throw a X or equivalent let's see if that's true it looks similar but if you notice we have less stacktrace information in fact all we have is grandparent method and then the the main method that's it the reason why is because it says okay that's the exception happened in the grandparent method it doesn't know about the parent method or the get number method it just knows this is where it happened in fact it says it's on line 24 which is this throw IX not the actual call that caused the exception and that's why we do not use throw X with what it does it rewrites that stack and it gives us wrong information so don't use throw IX another thing people might do is say throw new exception my input their own message here I blew up all right they'd say well the reason I do that is I want to have this more user friendly message to show to my end-users and if you run this it says hey I blew up more user friendly right yep but grandparent method and main that's all I got so that also is not the solution in most cases but there may be a case for you to create a new exception maybe you have a an issue where your application actually generates a new exception of a different type so let's go ahead and try doing that so we'll say new exception if you just have exception one of the cool things is it filters this list by anything that has exception in the name so you can look at the other exception types so for example we have the / 0 exception the dll not found exception the context marshal exception data misalign exception you know maybe we have maybe say well it's really a datum it's a line exception or an argument exception so you can actually create a different exception type than the original exception and you can say ok you passed in bad data hey that's great I changed exception type and I changed the message but we've lost all of our stack information so what we do well there's actually an option in the throw new exception to pass in an inner exception like e^x so what this does is it says ok this is the exception here's where it's at line 24 put our break point back in program CS and then run this code with the throw new argument exception okay so if we mouse over this it says you passed in bad data for the message and it is an argument exception but if we look at the inner exception it says the index was outside the bounds of the array that's our original message and it gives us the full path all the way down to the original get number method now it's kind of small but trust me it's there so it gives us our full stack for the original exception but it also allows us to have that that custom message and maybe even a different exception type in this case the exception type being that of argument exception so that allows us some extra latitude in how we deal with things we just need to look at that e^x dot inner exception so if we said you know e^x dot in our exception dot message or inner exception dot stacktrace we can get all that information as well now the only question is how do you kind of go through all those layers in case you're doing this you know five six seven times which you shouldn't be probably that is seen excessive but what you'd have to do is look to see if inner exception is null if it's not grab that stuck trace and then say okay is that inner exceptional and keep going down the rabbit hole until you finally get to the end where the inner exception value is null so that privately a while loop you'd say something like oh var inner equals e^x died in our exception and while inner is not equal to null then we're going to do console.writeline in our stack trace and then say inner equals inner dot inner exception so actually taking the inner exception from the inner and putting into inner and just kind of loops through if we run this we get the the stack trace in the first one which is these two lines right here grandparent and then main then we get the stack trace in the original which is get number then parent then grandparent because don't forget it stops a grandparent because that's where we generate the new exception and pass that new exception up grandparent to main so I kind of gives you your full stack and it gives you a way to capture all that information and the same time create a new exception and passed a new may more user-friendly message to the exception so hopefully that gives you a little more idea of of how this all works there's a lot of different moving pieces here the big ones to kind of remember are push a try-catch at the place where you're going to do something important with it if you decide you need to do something either simple like I seen you log it here but I need to let it keep going you can do this and then just hit throw just throw if you want to do a finally somewhere you can do a try catch finally and then just again throw or if you want to get a more complicated for some reason you can actually throw a new exception and just pass in the inner exception as this right here the the value the variable you created when you captured the exception so that's kind of exception and not nutshell we're not done yet but that's pretty much the philosophy around exception handling just make sure whatever you do I keep stressing this don't just eat exceptions that's bad that's really really bad that's where all kinds of bugs come into application that's where all kinds of vulnerabilities come into applications and that's where bad data is created from applications it just don't do it okay all right now I want to show you a couple of ways we can take this kind of the next level maybe in here we have this whole you know looping through thing where you say okay give us exception and all the rest but maybe we want to handle different exceptions different ways one of the ways we can do that is to actually have more than one catch block so over here we have argument exception so we'll say catch argument exception we can still call e^x and we have our catch block here now how can I call X still well because this variable has the the boundary of living only between these two curly braces so this variable has a boundary of only living between these two curly braces so I can actually call the same name and typically I do and the reason why because I know that e^x always is my exception variable that's a pretty standard abbreviation normally I don't like abbreviations for variable names I like to have it spelled out fully because it's so easy to forget the abbreviation is or mistake the abbreviation for something else it just it goes against best practices we want to fully write out what it is not Arg e^x it's argument exception just reads so much easier so but in the case of exceptions this is an exception I guess to the rule so and that's just to use e^x because it's it's pretty standard ly known that's what the exception variable is so maybe with the argument exception we say you know what I know that if you get the argue exception that I really want to do something different maybe I'll just say you gave us bad information bad user that's it I don't want to get the stack trace I don't get the message don't get the inner exception all the rest I just want to chide the user for giving us bad information that's it if I run this until I get open closed database connections you gave us bad information bad user now why is it that ran this catch block and not this catch block well what happens with a try-catch is it comes down it finds the first catch block that matches so it found argument exception that says is the exception of type argument exception why yes it is therefore run this code one into the curry races if not let's come down here and we'll run this code to show this actually works this way let's go here instead of doing throw new argument exception where it's going to do our throw I'm coming out the rest remember the original is not argument exception it's actually had a bounds exception we run this we get our original code back indexes outside the bounds of the array even though we have this catch block first because it's not an argument exception exception anymore it's a different type you can actually have these catch blocks for all the different exception types you might think you're gonna get if you want to handle them differently now exception is the base type for all exceptions which means that if none of the others catch it it'll definitely be caught by this one this is the lowest common denominator this is the one that everybody inherits from therefore we know this one this cache block will run if nothing else catches it first but that does mean order is important let's cut this code out and paste it down below and let's again throw our new argument exception and run it and oops I have build errors and it says a previous catch Clause already catches all the exceptions of this or of a super of super type exception so it's saying if you can't even do this because I know for certain that you will never arrive at this code therefore this is stupid don't do this it's useless code if even if it did compile you'd essentially be throwing this bit of code out so you have to have it be most specific to least the first one that gets picked up and matches is the one that gets the price so that's that's one thing note you can be more granular if there's a reason to do so don't just grab every different exception type put a catch for it and then do the exact same thing inside only pull it out if you wanted to do something different in this case we're saying we don't need a log every time a user gives us bad information we'd have logs full of exceptions that are just the user did something dumb we don't need to do that but for everything else we want to put it in the logs we want to make sure that we have all the information so we can track down what the problem is with this one we know exactly the problem is it's a user problem we can't fix users which we could all right so that's about all we need cover with exceptions we've covered how to catch them doing a try-catch block we got a little complicated with the multiple catch blocks and the finally over here but the basic stuff is try area in here is is run instead of try and so if anything causes an exception he'll jump right to a catch block and then run that code instead so that's that's a simplistic version of it the one thing be careful of is I declare this result inside of the Tri therefore I cannot use this variable outside the Tri that also means if I were doing logging at this catch area right here I cannot log the value of result in case we actually hit this value before we have the exception the exception happens down here I'd have a value here and I can't get to it to log to say okay I got back a value of 18 and then the whole world blew up so what you need to do is if you need to capture this you would need to declare this variable outside of the Tri so just just remember that Cree braces mean boundaries anything inside has boundaries that's created is not visible outside those boundaries that's why we can have e^x more than once so remember that declare any variable you need to have in your catch outside or try that also means you cannot return result because result is declared in here therefore you have to declare it outside so just some things to think through but that's that's the basics of try catch make sure you push your caches high enough that you get your full stack trace if possible or at least as much as you need and also high enough that you can actually talk to the users right where you're at so make sure you catch it in there in the user interface if possible that does mean that your library might just go ahead and throw some that's okay even Microsoft's libraries the list and say hey I can throw these exceptions for example the file library might have the file not found exception if you give me a file name and it's not on the hard drive where you say it is that's an exception now again it's a user problem but it's still what I do I throw exception and say I can't do that it's also ok for your code to actually create new exceptions this could even be in the try somewhere maybe you have code like this where it says if position is less than 0 for example throw new out of index out of range exception the value must be greater than or equal to 0 that might be ok now that there's probably other ways to deal with it besides an exception but if you are writing just the library and don't have access to the user interface that might be a good solution throw an exception let bubble up the chain don't have a catch here just let but let the chain and then let the caller deal with the exception because that's what it really is they gave you bad information you can't just continue on so it is ok sometimes to create your own exceptions if that's the right choice just don't just do it just to do it ok don't just say I'm always gonna throw exception unless the values are inside our range well if you're in the user interface just pop a box up it says hey you can't do that yet doesn't even exception just needs to be a an error check so that is possible for you I do and again there this is some complexity that we're adding to the whole try-catch again it comes back to try catch at the right location don't just eat errors actually make sure you handle the errors and clean up any bad data you have in your system and if possible alert the user to what's going on all right if you have any questions please go ahead and leave them in the comments down below and let me know what still confuses you there are some kind of advanced things we can do for example in asp.net MVC we have the idea of the exception handler that actually displays on to the webpage we can have you know the user friendly error messages that show for mote users and we can have the the full stack trace for developers if they're on the same machine as the MVC app all that good stuff we can do we're not cover that in this video to do that it's kind of outside the bounds of general exception handling but I just might let you know there is some more advanced stuff you could possibly do but what I'd recommend is use this try catch block especially at the UI layer whenever you have code that might cause a problem don't just wrap your entire code set in a try-catch probably not the right idea because that can cause some other problems but just wrap around the stuff that you need because you can also have more than one try catch block that way you don't have to have multiple you don't have to clear all your variables outside the try you know there's a whole lot of reasons why you don't just wrap the entire code set in a tried catch but make sure you catch exceptions properly make sure that you deal with them in a way that's appropriate and make sure you let your users know there's a problem there will be a link down the description that has a link to my blog post on this topic it also has the source code we did right here just as it is you can play around with it and try it out and see which how it works for you and just kind of save you from retyping things all right so check that out in the description below alright I think that's it as always I am Tim Corrine
Info
Channel: IAmTimCorey
Views: 103,696
Rating: undefined out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, training, how to, tim corey, C# training, C# tutorial, try catch, c# try catch, exceptions, c# exceptions, c# exception handling, c# exception handling best practices, c# exception handling example, c# exception tutorial, c# exception stack trace, c# exception message, try, catch, finally, rethrow, throw, throw ex
Id: LSkbnpjCEkk
Channel Id: undefined
Length: 59min 45sec (3585 seconds)
Published: Fri Feb 23 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.