Exception Handling in C# step by step using example

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so first let us try to define what exactly is exception exception is nothing but it is a kind of an event a bad event which happens and it disrupts your normal flow of your application for example you can see that I have a very simple function you are called as divide right and this divided function actually divides two numbers right so you can see that I am calling the divided function and let us say I want to divide 10 by 10 right so if I run this it it gives me one and that is right okay and after that I've just put a thank you message right so this is good this is my normal flow of the application in this normal flow it goes and it divides two numbers but now let us say that I go and say divide 10 by zero so if I try to divide a number by a zero I will get a divided by zero exception isn't it so if I run this application now you can see that the application has crashed and it says that there is a divide by zero exception and it is not allowed so this is termed as the exception exception is that my normal flow of the application was to divide the number and say thank you but now that this exception has occurred it just crashes the program and just waits for things or it reads it just ends the program right so this is termed as exception now definitely when you talk about software applications exceptions are going to be there it's only the thing is that you know have you handled that exception or not so for example in this case also we have exception so we need to go and handle this exception so first point I need to tell you that if you do not handle the exception then what happens is the application throws the exception to dotnet and dotnet just shows that error on the screen right so if you see at this moment because I have not handled the exception the application throws a error to the dotnet framework and dr. favor just shows it very shabbily on such kind of on the screen in a very bad way right so so in order to handle this gracefully and show a very nice message what we can do is we need to you need to go and say that okay I want to go and handle this exception so I will put a try a try block is nothing but it is the area you know where you X where you expect the exception will occur for example I expect you know that probably something bad can happen when I try to divide this then I call and try to call this divide function right so wherever you expect that the error will happen you will put a try block and to catch the exception you will say catch exception e X so now basically a you know when I accept it occurs within this try block scope it will actually send the control of the program to the catch and this catch I will go and put a nice line here so console dot write line error has occurred sorry right so now if I run this my application will throw a neat message you can see sir it's a very neat message out there error has occurred sorry right okay but definitely you know this is not more than enough the first thing is I need to show what exception has occurred right so even though if you see the previous message was shabby but it was telling the end user that what exactly happened right and here I'm just putting a generic message saying error has occurred sorry right so what he can do is you can go and use this e^x object which comes out here so we can say that okay use this es object and you can use something called as the message property of it and this message you actually can get the exception message so now if I go and run this so now it shows that yes attempted to divide by zero okay so you can see now this is very clean as compared to the previous one you know where was where it was showing too much of things outright good so we are able to handle this exception and we are able to show a neat message to the end-user and it looks good but now there is one problem over here the problem is that it is not showing me the thank you message what I want is that okay the exception can occur in divide function that is fine but I want him to show the thank you message in respective the exception has occurred or it has not occurred so if you see for now what is happening is look at the way how the flow is moving I put debug points here so if I run this so it goes here the exception occurs and you can see it did not go to this line it straight forward came to catch so the second point to remember about shisha exceptions is that wherever the exceptions occurs after that you know if you have any kind of code those code will not be executed right but if you want that the code should execute irrespective you have an exception or not then what you should do is you should use something called as the finally block the finally block R is nothing but you know it is something you know which will run irrespective you have an exception or you do not have exception so what will happen now it will try to divide 10 by 0 it will it will not succeed it will show me the exception and after that he will run the finally block right so now if you see the output you can see that it says ok I try to divide by 0 and it failed and after that it is now executing the finally code as well so remember that you know C sharp exception handling has three important keywords one is try so try is the place you know where you expect exceptions can happen catch is something you know which will be executed when there is an exception in the Tri section and finally is a section which will execute irrespective you have an error or you do not have an error now one more very interesting thing about shisha exceptions here are that c-sharp exceptions are propagated from the source from the from the collie to the collar okay for example now over here let us say that we have one more function here called as arithmetic function now this automatic function takes in two numbers but internally he calls the divide function right so you can think about that this automatic function is a wrapper on the top of divide function and your main function is calling the arithmetic function so now look at the flow here so you have a main function the main function calls arithmetic function and the arithmetic function calls the divide function so the main function is the caller after that he calls our thematic and our thematic calls the divide so now when any exception occurs in the divide it actually first throws that exception to the arithmetic function and then the automatic function throws that exception to the main function or until it gets handled so basically exceptions in shisha are propagated to the caller okay so nothing will change you know I will get the same kind of error what I was getting previously so we can see that it shows me the same error here attempted to divide by zero so the exception is same but internally now the exception is propagated from divide to automatic and from our thematic to the mean now this propagation architecture is good but now it can have lot of problems for example let you know when you talk about serious applications you know serious applications are divided into lot of layers so they have UI layer then they have a service layer then they have a business layer then they have a data layer right so let us say that you know there is some problem in one of the layers then the errors get propagated and while you are on production or while you are debugging you would like to know that on which layer the exception happened so over here I would like to know that yes the exception happened in divide or did except should happen in automatic right so for that you know what we have here is we have something called as this ax dot message just displays the message but if you say e x dot stack trace this stack trace displays you know how the call happened and where the error happened so if you run this so if I run this it gives me a very shabby message definitely but it tells me lot of things internally so it says that the exception happened in divide after that it was thrown to arithmetic and arithmetic did not handle it so it was then thrown to main and then main handled it right so basically uh you know the stack trace actually tells you more details about how the whole call happened and in which layer the problem was now till now whatever exceptions that has occurred it has occurred by the dotnet system itself so in other words you know this the exception occurred over here and dotted system itself through the divide by zero right but now let us say that you know we want to go and throw our own exceptions for example now I will say here you know what if num1 by any chance is less than zero right or num2 is less than zero then i do not want this program to proceed ahead so what I can do I can say here okay so if num1 or sorry or num2 is less than zero right I've got to throw exception here so you can see now throw I will say throw a new exception negative numbers not allowed right so over here now I can say 'hey x dot message let me go back again to my message so that we can see it in a more clean way so now when I pass the zero exception the the the divide by zero gives me zero but if I try to pass some negative numbers right then it will throw me exception saying negative numbers are not allowed so you can see now I have created my own exception here a kind of a user-defined exception which says that a negative number is not allowed so if you want to throw your own exception then you need to use the throw keyword right and if any exception happens from dotnet they just get thrown out and you can catch them and you can you can act accordingly also I would like to bring to your notice that there are lots of ready-made exceptions exception types given by dotnet for example one of the things which have which we have seen is divide by zero but you can have null reference exception you can have IO exception you know when you are reading from a file you can have a stack or flex efficient you know in case you are calling functions calling himself and etcetera right so you can see that there are lots of ready-made exception objects you know given by dotnet and these exception objects you know you can catch and you can act accordingly right now if you see from this divide functions there are two kinds of exceptions which are thrown out so one is my own exception right and the other one is the / 0 exception so from here / 0 is getting thrown out right and from here my exception of negative numbers are thrown out right now if you see on the caller side there is only one catch which is handling both of them so both this this catch is like a generic thing you know which is handling both of the exception so irrespective it is an exception which is of what / 0 or it is the exception of negative numbers you know it is handled in a very generic way what I would like to do is I would like to go and treat them specifically for example if you say okay / 0 if somebody's attempting I have got to still continue the program by dividing it by 1 right so I would like to go and handle both of these exceptions separately and treat them in a different way so for that what he can do is you can have multiple catch here so you can see here okay when it is a generic exception just catch over here but when it is a nobody call a / 0 exception then what you do what you do is that you try to divide by 1 so you will say that / 0 not possible / 0 not possible 0 not possible attempted corrected I will say corrected to 1 right so you can see now over here what I will do is I will take whatever it is a value and I will try to divide it by 1 so for example now look at this if somebody is trying to divide by 0 what I'm doing is I'm not I'm showing him a message saying that see you try to divide by 0 which is not possible so I am correcting it to 1 so what we are done is you know we have made the denominator as 1 right so you can see that I'm handling the / 0 exception in a very different way and I'm handling my normal exception in a very different way so you can have multiple catch statements and you know with those multiple cache statements you know you can treat each one of these exceptions in a separate way so now if I run so you can see now there is a divide by 0 exception which will happen but what I am doing is I am saying that okay / 0 not possible correct it to 1 and the value is 10 and thank you right and if I try to now divide by a negative number then what happens is my genetic exception comes in and you can see that it says okay negative numbers not allowed and thank you so basically now you know I am treating these exceptions very specifically and acting accordingly now remember that whatever is the you know whatever is the child exception that has to be kept at the top for example now let us say I go and change the sequence here let us say that I go and put the catch exception here now look at this okay so if you see here now it says that the exception that is thrown here right the previous exception over here is catching all the exception it can it will never come here means what as I have said that you know we have lots of exceptions in dotnet you know like we have divided by 0 we have null reference we have invalid cast exception and so on but at the end of the day all of these exceptions you know inherit from a parent class called as system dot exception that is this one right so now what happens is if I put the catch over here you will catch everything and all the below catches will get bypassed again I repeat this exception is the parent class and the other exception classes are the child class which are derived from the same so what happens is if you put the catch block at the top it says that a previous sketch already catches all the exception because it is a super type right so remember that your generic exception should go at the last in the sequence and your specific exceptions should go at the top right or else it will not work now let us say I want to put a validation here you know where I will say that if num 1 is equal to num - then throw exception saying that you know like the value is value is 1 right so means I do not want to even do the division because if both the numbers are equal then what is the point of doing the division right so let us say if I if I get num 1 equal to num 2 then what I want to do is I want to throw a new exception saying that number our numerator and denominator are same right and and it throws exception right now the problem here is that you know both of these exception that means a negative number exception as well as the numerator and denominator exception both are coming over here now what I want to do is I want to now differentiate between both these exceptions now both of them are user-defined exceptions so both I have created by using the throw new exception but now I want to say that okay if numerator and denominator I throw exception I catch and I just show the value is one right so I want to now differentiate between this exception and this exception okay and both of them are user-defined exceptions so for that what you can do is you can go and create your own exception class so you can go and say here okay so create a class called as a numerator numerator and denominator so or or numerator and denominator equal okay numb denno equal okay so in order to create your own exception class you can go and inherit from the exception class here so you can see this exception class is the system dot exception the top exception class and over here you know we can go and write our own exception logic what we wish so you can now see that I have created a separate exception class here called as numb denno equal and on the constructor I am passing the error message and the constructor the current class constructor is passing it to the parent class so now what I can do is I can say here so throw new numb demo equal exception right must be by putting the word exception you can come to know that this is exception so I'm go and do that so numb denno equal exception and what we can do is we can go and catch this so I can go and catch this over here so I can say catch numb jano equal exception and I will just say console dot write line one right because this is exception but you know I'm handing it very separately right so now if I try to pass him one comma one look at this so it throws up a num demo exception it just says our exceptions must expect a return type throw new must have a return type it's a constructor why is it asking for a return type oh my bad I'm becoming old finds right so because it's a constructor right so I change the class name I also need to change here that's fine so I'm going to go and do a control affine ow sorry for it so now I should get one this is good right and for the others when I pass - I get my normal exceptions so control fi and why again one this should actually throw me exception or not here it is minus one so if I put minus one I get the negative number exception if I put a zero I get my system exception right if I try to divide it by zero I get the system exception right so basically you can see now we have multiple catch blocks we have multiple try blocks we have a custom exception which is thrown we have the system exception which is coming up now also I would like to make you aware of something called as exception swallowing okay exceptions rolling means what for example now think about the situation over here are in the arithmetic let us say I catch the exception right and I create a new generic exception from here saying ah you know something bad happened look at this if you remember what we were doing is our main is calling arithmetic arithmetic is calling divided right so when any propagate many when any error happens it propagates to the our thematic and what now arithmetic is doing he is actually catching the exception he is catching all the exception in respective it is a numerator denominator - error or whatever right R divided by zero is catching up and his overriding the exception with a very general message called as something bad happened something happened something bad happened right now with this what happens is in our main I know when you when we are catching the exceptions over here right it always shows a generic message you can see something bad happens so in respect to whatever it is - one again something bad happened so now you know what is happening is because you know the middle layer has overridden the exception all the previous exceptions have gone off right so what what should really you know means what you should be doing over here is you know rather than saying throw new exception you should say throw a X so whatever exception is coming from the bottom just throw it to the top okay in case you want to add something new to it what you can do is okay you can add something new but do not forget to append that the exception which is coming from the propagation right so you can see now what I have done is okay I have added something new to it something bad happened but also what I am doing is I am I am keeping the original exception intact right so with this if you see now something a bad has happened what is it negative number not allowed okay so basically first thing avoid throw new exception until you want to go and add something new to it along the propagation chain or else the best is just say throw X you know basically it just takes whatever is in the stack and throws it to the top so if you see now this will have the same effect what we had previously right so this is termed as a what you call exception swallowing you know in case in between somebody goes and says throw new exception the full previous stack is overridden so this was a very small video you know in this video we were trying to understand see shop exceptions and you know what are the different things inside see some exceptions so I hope that you enjoyed this thank you very much [Music] [Music] [Music] [Music]
Info
Channel: .NET Interview Preparation videos
Views: 37,485
Rating: undefined out of 5
Keywords: csharp exception, exception handling step by step, explain exception handling in c#, exception handling in c sharp, handling exception in c# program, c# interview questions and answers for experienced, interview questions on exception handling, how to handle exception in c#, exception handling tutorial c#, exception handler tutorial, what is exception handler, handling exceptions in c#, exception handling in c# application, c# program, handle c# exception, exceptions tutorial
Id: 9jmA0UO45-Q
Channel Id: undefined
Length: 24min 53sec (1493 seconds)
Published: Sun Dec 04 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.