Exception Handling In Python | Exceptions In Python | Python Programming Tutorial | Edureka

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey everyone this is uh Nero's from Adi Rekha in this session let me walk you through on how you can learn and make use of exceptions in Python guys this session is intended to be useful for anyone considering to kick-start their learning about Python and need some insight on how you can go about making use of exceptions to make coding very easy for you so the focus is basically on approaching the language in the easiest way possible and to find out what it has to offer to the community and all of the learning enthusiasts out here so let's begin by checking out the agenda for the session we'll start by checking out why we need exception handling first later we'll check out what an exception actually means followed by that we'll be walking through the entire process of how we can handle an exception and lastly we look at how easy it is to code with Python where we will take a programming approach and learn the concepts through code now that we're done with the agenda without further ado let's begin by checking out why we need exception handling well to understand the concept let me quickly walk you through a very simple scenario consider the case where you're dividing any number by 0 what will happen can you divide a number by 0 you cannot correct but how would a kid approach this problem the kid would think that you can actually use regular division to divide something by 0 so you're dividing something by nothing so it stays the same something like this right little does the kid know that this is wrong now check out how a programmer would approach the same concept well it is established that dividing by 0 is not possible mathematically so as programmers we know it is not correct so this basically leads to two cases either an exception or an error so a Python program terminates as soon as it encounters an error well in Python an error can be either a syntax error or an exception and it is as simple as that well let us actually divide by 0 for fun guys so this is what happens in Python Python presents us with this beautiful error message saying that it cannot divide something by 0 well in fact let us head to PI term which is my eye for coding in Python so we can actually walk through this practically so guys here I am in my Python so let me quickly go over and type out some simple code for you guys so let us start with y equal to 10 we can actually print Y by 0 now so let me quickly go ahead and run this in the console so as you can check out it's a zero division error division by zero is not possible so you cannot divide anything by zero so let's establish that at this point is that was good enough right so let's get started then let us quickly check out what exception handling actually is well guys to get a clearer picture of what that is we need to start with understanding the definition for both exception and exception handling when what is an exception guys an exception is an event which occurs normally during the execution of a program that disrupts the normal flow of the program's instruction so instead of the program actually executing evenly and nicely there is actually a disruption in between the curve so this we basically call as an exception so next what is exception handling guys this is the process of actually responding to an occurrence of an exception as simple as that so basically the process of responding to the occurrence during compilation of exceptional statements which require special processing is actually what as exception handling guys so this is basically done because of the change in the normal flow of the program execution well it is a very simple concept and I'm sure at the end of this session you guys will agree well at this point what do you think of exception handling in Python guys head to the comment section and let me know what you think so we can interact there and now that we know what exception handling is we need to understand how the entire process of exception handling works so let us check it out first let us walk through what happens in Python so let us say the user makes an error what happens next guys when you think about it it is either the user that finds out the error or Python will actually tell you what the error is correct so once you know what the error is and you know where it is you can basically start analyzing it to know if it is fixable or not well if it is fixable how can you go about doing that well if it isn't nothing to worry guys python is so good that no matter on what level you mess up there is always a way out of it guys so now if it's fixable how can we handle the exception check out the image on the right side so we need to first find the error if we cannot do it Python will find out for us well next is to make sure you take caution while coding if you think that there is going to be an error in that particular piece of code well remember the word try at this point all right and later we'll actually fix the error and we call this a sketch just remember the keywords for now and we'll be walking through these in detail in the following slides in fact let us begin by checking it out right now so guys these are some of the important terms that you need to take a note off before starting to code and understanding exceptions so first we have tri well tri is basically the keyword which is used to keep the code segments under check so whatever code you put under Tri is actually the code under scrutiny guys and next we have except well except as the segment which is actually used to handle the exception guys so how do we know that the exception is occurred if our piece of code in the try block has actually caused an exception then we can handle it in the except block and how do we use else well else is basically run when no exceptions exist guys and lastly we are finally finally we will run even if there is an exception finally we will run if there is not an exception as well so I want you guys to note this at this point of time and this will help you a lot in the coming slides guys so enough coming back to Python this is what it visually looks like we first have the try block where we run a piece of code and next we have the except where the code actually runs only when there is an exception in the try block and if there are no exceptions then we run the else block guys and lastly no matter what exception or no exception we run the finally block always guys sounds simple right well it actually is and now that we're familiar with the process of exception handling let us check out how we can go about understanding this using Python practically guys well syntax errors occur when the parser detects an incorrect statement well check out the tiny arrow on the left side here well this is basically to indicate where the parser ran into the syntax error well in this particular example there were too many brackets right so there was an extra closing bracket well if you actually remove it and run it you will actually get a different error this time we'll check on the right side part of the code well this time you actually ran into an exception error well this type of code occurs whenever syntactically correct Python code results in an error guys so the last line of the message indicated is what type of an exception error that you actually ran into well in this particular case at a zero division error and it says that the integer division or modulo by zero is not possible so this is basically the same case that I showed you in PyCharm a while ago but instead of showing the message exception error Python details what type of exception error was encountered well as I mentioned in this case it was a zero division error right well python comes with various built-in exceptions as well as the possibility to create self defined exceptions as well and now that we are clear with that let us check out how we can go about raising an exception on our own so we can basically make use of race to throw an exception if a condition occurs the statement can be complemented with a custom exception well if you want to throw an error when a certain condition occurs using race you can actually go about it like the following piece of code you actually see on the screen and when you run this piece of code you'll be greeted with the following output guys so it says exception X should not exceed 5 and the value of x was 10 so let me quickly jump back to PyCharm and we can execute this there so guys I'm in my Python right now and I quickly typed out the code for you guys so let me quickly go ahead and run it and we can check out the error as you can see it says exception X should not exceed 5 and the value of x was 10 perfect right so let's quickly jump back to the presentation to check what's next so the program basically comes to a halt and displays our exception to screen right so this basically offers clues about what went wrong and now that we're clear with that we can actually proceed to checking out the assertion error guys so instead of waiting for a program to crash Midway you can actually start by making an assertion in Python well we assert that a certain statement is actually met and if this condition turns out to be true then excellent the program can continue but if the condition turns out to be false you can have the program to throw an assertion error exception for you guys well have a look at the following example on your screen well this is basically where it is asserted that the code can be executed in a Linux system guys so if you run this code on a Linux machine the assertion passes if you were to run this code on a Windows machine the outcome of the assertion would be false and what would happen well definitely the result would be something like this right so it would basically present us with genero and says that the score runs only on Linux right so I'm using a Windows just up in this particular case so let me quickly open up my PI thumb and then we can actually run this piece of code to check out our exception guys so I'm back in my PI charm and I've typed out the code guys so let me quickly go ahead and run this as you can check out since this is a Windows machine it says this code can run on Linux only but this particular case this assertion would be true if you were actually running this on a Linux machine base so if any of you guys are using Linux machine make sure to try it out and on that note let's quickly come back to the presentation base well in this particular example throwing an assertion error is the last thing that the program will do the program will definitely come to a halt and it will not continue base but what if that is not what you want what if you want something different from this or that you want the program to continue while displaying an exception for you guys well now that we actually have a fair idea about how we can go about understanding exceptions let us dive right into the heart of exceptions now yes I'm talking about the try and except block guys so basically the try and except block in Python is used to catch and handle exceptions well Python basically executes code following the try statement as a normal part of the program the code that follows the accept statement is the program's response to any exception in the proceeding try class guys well as you saw in the earlier example that I actually showed you when syntactically correct code runs into an error Python will throw an exception error and this exception error will actually crash the program if it is unhandled guys so the except Clause determines how your program response to these exception guys so instead of actually crashing our program we can actually tell Python what to do when this particular exception occurs we'll check out the following function guys so this function can basically help us understand the try in the except block well the Linux interaction function can only run on a Linux system the assert and this function will actually throw an assertion error exception if you're using it on any other operation system apart from Linux well we can actually give this a try in Python so let me quickly open up that so guys i'm quickly on my PyCharm so let me go ahead and select this Center on it well this won't say anything right now because well if it was actually a Linux platform the message would have been printed right so let's quickly jump back to the presentation so basically if we on the tiny piece of code you see on the bottom the way we actually handle the error in this particular case is because we gave out a pass right well if you were to actually run this code on a Windows machine you would get the following output which is already on your screen right so it is a blank output you get nothing well the good thing here is that the program actually did not cash but it would be nice to see if some sort of exception occurred when you actually ran your code well to this end you can actually change the pass into something that would generate an informative message like this check it out so let me quickly go ahead and run this in python well as you can check it out it says the Linux function was not executed right so basically this happened because I am on a Windows machine guys so let's go go back to the presentation and guys when an exception occurs in a program running this particular function the program will continue as well as inform you about the fact that the function call was not successful well what you did not get to see you as the type of error that was actually thrown as a result of this function call - so in order to see what exactly went wrong you would need to catch the error that the function threw well check out this particular piece of code I have for you guys so here is basically where we actually captured the assertion error and we print the output message to the screen so we have a try block we have the same function and we have accept as error right so we're gonna print what type of an error it is followed by a message for us right so running this particular case on a Windows machine will actually give us this following output guys so it says function can only run on Linux system and whatever you have chosen in the print block is actually being printed for us so let me run this in pycharm so they can check it out we have the message printed right so it was the same as I told you so it was the same message as I told you before heading back to the presentation well in the previous example we actually called a function that we wrote ourselves right and after that when we actually executed the function we caught the particular assertion error exception and then we printed it on the screen well I have for you another example where you actually open a file and use a built-in exception guys in fact let us dive I went to pycharm and we can actually run this and we can come back and take a look at the output so guys I actually came into PyCharm and I actually ran that particular piece of code why does it say could not open file log well guys basically if the file dot log does not this the block will give you this output right so it says the file could not been opened well this is an information message and our Python program is actually still able to continue to run it has not crashed right well actually in the Python documentation you can see that there are a lot of built-in exceptions that you can make use of and here is one exception that I have for you guys that you can check it out so the exception file not found at all right so basically this is raised when a file or directory is requested but that doesn't actually exist and this is just one among many that Python offers to us guys well to catch this type of an exception and to print it on the screen you would actually use this following piece of code guys so in the try block we're actually gonna open it as file and we're gonna read something present in it guys we can accept it by pushing a file not found error as an object and later we actually end up printing that object right so let me quickly go into pycharm and we can check it out well as you can check it out we have error number two which has no file or directory right so it's perfect well you can have more than one function call in your try Clause actually guys and anticipate catching various exceptions as well well a thing to note here is that the code in the try Clause will actually stop as soon as an exception is encountered but there is one important thing that I want you guys to note down is that by catching an exception it basically hides all of the errors guys well definitely there are some unexpected errors in your program right when you're catching an exception and even these are completely hidden from you well this is why basically you should avoid using Bare accept statement clauses in your Python programs guys so instead basically what you can do is you can refer to the specific exception class that you want to catch and then handle those particular exceptions guys so look at this following piece of code I have for you so you are basically you first call the Linux interaction function and then later actually try to open the file guys so let us quickly jump into pycharm and we can actually check it out so as you can see I actually executed the program guys again if the file doesn't exist running this code on a Windows machine will give you their output right so it's basically says that the function can will run only on a Linux machine and then we have actually printed something guys well what we actually did here is inside the try clause we directly ran into an exception immediately and will not get to the part where you'll actually try to open our file or log right now basically when you actually run it on Linux machine it's gonna says no file or direct found check it out yo guys so this is the windows output that you get and this is the Linux output guys well at this point let us take a quick break and check out what are the key takeaways of this particular module guys so basically a trike loss is executed up until the point where the first exception is encountered and inside the except clause or the exception handle of what we basically call it we can actually determine how the program actually should respond to that particular exception and we can actually manipulate multiple exceptions and differentiate how the program should respond to each of them right and lastly we actually learned why we should avoid using barracks at clauses guys and now that you're clear with this next up I have for you is the else clause guys so basically in Python using the else statement you can instruct a program to execute a certain set of code only in the absence of exceptions guys well check out this following diagram on your screen so basically in the tripod we have the code except when we actually want to handle the exception or else in case there is no exception we're gonna run the piece of code that comes in under else case so let me quickly walk you through the code guys so here is basically the same Linux interaction function and we have an assertion error here and we actually are going to print the error right so else if there is no assertion error so we're gonna have an else clause and we're gonna print saying executing the else clause right so let me quickly open up my pycharm and we can run this piece of code guys so as soon as I go ahead and run this it says function can only run on a particular Linux system right so again check out the output it says the function can run only on Linux systems right so in this case I have a Windows machine so we're actually not printing the except clause here but if you were running this on a particular Linux machine this is the output that you would get guys so it says doing something and executing the else class correct this happened because if the program did not run into exceptions any exceptions right so else Clause was actually executed well you can actually try to run the code inside the else clause and catch possible exceptions there as well well again we have the same Linux interaction you are we're gonna print it right so the Linux output says doing something and no such file or directory found well this is basically for the else clause and we using the same file example here but then we are actually trying to catch an exception in the else block as well so the output is pretty much straightforward as well right well from the output you can actually tell that the Linux interaction function actually ran well because no exceptions were encountered and attempt to open file dot log was actually made and that file did not exist and instead of opening the file you actually caught the exception which is the file not found exception pretty simple right and I hope you guys are clear with all of the concepts that we discussed until now and next up we need to check out how we can actually use the finally Clause guys well to begin with imagine that you always had to implement some sort of action to clean up executing your code guys well Python basically enables you to do so using the finally Clause have a look at the following example guys check out the workflow on your screen I'm pretty sure we're all familiar with try accept and else at this point of time right so this is the chronological order that you need to go into first you have the type to check for an exception then we actually handle if there is an exception using the accept or else if there is no exception we're gonna print whatever is there in the else block and lastly we have something called as finally guys so no matter what we're gonna execute this in case if there is an exception the finally block is going to run in case there is no exception finally block is going to run there as well so let us quickly check out a coding example guys so basically this is the particular code I have for you guys and let me jump back into my Python and we can actually execute this so guys I'm back into my PI chump so let me quickly go ahead and run this well as you can check it out it says that the function can only run on Linux machines this is because I'm on a Windows machine right now and no matter what right so exception or no exception we have this message which is cleaning up irrespective of any exception guys so this is basically the use of finally guys and that is as simple as it gets so it's pretty much simple right well try except else finally all of this is a really simple concept and once you understand what it actually does you can go about doing a lot using Python based well no matter what the Python application is there is a very good chance that you'll actually make use of exceptions case well on that note let me quickly summarize the entire session for you guys well in this session we covered the following topics well basically we started out with introduction to exception handling and later we looked at why we actually need it right and then we checked out the following concepts in the screen so we checked out race we checked out Ezard we checked out tryi we checked out accept else and finally guys well guys I would suggest you actually take a screenshot of this right now or take a note of all of the keywords and how you can use them in Python guys so this will actually take you a really long way and your Python courier and knowing exceptions in Python is always an upper hand when you're coding guys and guys it is at this point I would like to tell you that I have curated an in-depth video on Python meant for beginners I am getting some really good feedback on that and I want you guys to check it out and let me know what you feel about it guys so we also have in-depth videos for all of the major Python concepts and so much more on the channel I'll leave a link in the description box below so make sure you can check it out so that is it for the small session guys I hope you took away some real good points from here and that this helped you kickstart your Python learning so thank you guys you know what to do if you have any queries leave a comment and subscribe to our channel for more information on the latest technologies and all of the courses offered I hope you have enjoyed listening to this video please be kind enough to like it and you can comment any of your doubts and queries and we will reply them at the earliest do look out for more videos in our playlist and subscribe to any rekha channel to learn more happy learning
Info
Channel: edureka!
Views: 46,730
Rating: undefined out of 5
Keywords: yt:cc=on, exception handling in python, exception handling in python 2.7, exception handling in python with examples, error and exception handling in python, what is exception handling, try except finally python, exception handling python 3 tutorial, try except finally, try except finally python 3, try except finally else python, python programming tutorial, python programming practice, python tutorial videos, python online training, python training, edureka
Id: NMTEjQ8-AJM
Channel Id: undefined
Length: 21min 29sec (1289 seconds)
Published: Thu Feb 07 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.