Exception Handling in Python | 53

Telusko · Intermediate ·🤖 AI Agents & Automation ·5mo ago

Key Takeaways

Explains exception handling in Python

Full Transcript

Welcome back aliens. My name is the Reddi. It's time to talk about exceptions in Python. Now we have talked about the good things. Right? Now we know the basics. We have talked about oops concept. Now when we talk about exceptions, they are something which you have to handle. Now what if you don't handle them? First of all, what is exception? How it works? How to handle them? So we'll divide into multiple segments in for this particular topic. But let's talk about why you have to handle certain things. See when you build applications or as a user of the application whenever you use any app it can be on your phone or it can be on your desktop you expect them to work right and it you expect them to give you the response which you are expecting right? So a lot of expectations there but the point is the app should work. The app should work smoothly and then it should not crash. But then if you talk about the kind of application which you are using. So there are some applications which are not very critical. There are some applications which are very critical. Now applications which are not critical. Example let's say calculator. Now of course if you want to calculate something you can do in your mind but we are lazy. So you open your calculator and you start typing something. And then what if something goes wrong and your app crashes? That's fine. I mean, of course, you'll be angry, but then you can simply reopen it, enter the same number and you're done. But what if the app which you're using is critical. Now, see, when you talk about app, you pictureize something, right? You have an image of an app in your mind that it it should be visible and then you are clicking something. But if you talk about the hardest which we use, they are using a software, right? example the plane the car the MRI machine all these are actually running on softwares which you can't see uh because that's how the things work right you see the hardware and then the software are running behind the scene even if you buy a new car now all the modern cars they have lot of softwares with it so they have a lot of semiconductors and softwares and what if you are on the highway and something goes wrong with the software and it crashes okay it shouldn't happen but then you can see the impact right so these are missionritical softwares is for the flight for the uh for the MLI machine and banking applications. So you have to make sure if something goes wrong of course things will go wrong but it should not crash the software. It should not stop it working. So those things which comes are called exceptions and you have to handle them. Okay. So we'll divide into multiple se sections for this particular video. First we'll talk about what what are exceptions and uh in fact we'll start with different types of errors. we'll move towards exception and then we'll see how do you handle it. Now let's talk about errors here. Now if you talk about a code, a code can have different type of errors. Okay, in fact to show you that I will open my in fact any code. Okay, randomly I will jump to let's say this code. Okay, which is fact recussion. So we have done this before. Now if you have reached till exception I guess you know what is factorial is and recussion is. So let's say if you talk about this code and in this code there can be different types of errors. The first error could be a compile time error. I don't know why I was saying logical error but yeah compile time error. Now what is a compile time error? Now whenever you make mistakes with the syntax okay so when you play around with or you're not doing something correct as per your compiler or the interpreter it will it will complain. Example let's say if you talk about this code what if you make a mistake here. So instead of saying single f you typed double f as soon as you do that your IDE in fact if you're not using ID if you're using a normal editor your your Python interpreter will give you error but your ID says what you're doing this is a error there's nothing called deaf here okay so as a developer you know okay you have written something wrong and your compiler is shouting at you or your ID is shouting at you that's a compile term and one of the most easiest error to solve is the compile terminal is because as a developer when you're typing that you can see the errors. So sometime if you write something in the if condition you might not see the error by the ID. For example, if I write break here, okay, it gives an error. Yeah, if you write pass here, there's no problem. If I say PAS, uh you are getting a warning, but you can see there's no error on the screen and it's actually an error. There's nothing called pass, right? So I mean PAS, not PASS. PASS does exist. So you got the point, right? So at least your ID your interpreter will help you. So when you run that it will say hey what is pass I don't know the second kind of error which you normally get is a logical error. Now this logical error is when you have some logical mistakes which you have done example let's say in this code if you try to run this first of all I have to uh go to the folder cd basics clear and now if I try to run this which is fact_reussion py you can see we got 120 that's what the factorial of five is but if you make a mistake here let's say if you instead of returning one you returned two now in this case you will get a different output and that's 240 which is incorrect And this is a mistake, right? This is a logical error. There's nothing wrong with the syntax. Everything works. Now, since you made a logical mistake, you will get a different output. Now, this is actually tricky. Okay? So, this is difficult to find this type of errors. Is because if you know for five it should be 120 and if you get 240, then you know that's a problem. But what if you have written something and you're getting an output and you're not sure if that's a correct output. Example, let's say if you're fetching something from the database. Let's say you want a name of an employee with the ID5 and if you get a name let's say Naven and you expected was Hush and you don't even know you're expecting Hush you got Naven you're happy I mean that's what you get in college and uh dummy projects you get some output you you feel happy but that's a mistake right you got a different answer or you got a wrong answer now to solve that basically we have a team right so as a developer you test it first then you have a testing team who will test it and then if something goes right or if everything goes right then only you will make it into production And in production as well sometime it breaks and sometime it's not giving the correct output. You do AB testing you do testing with your client and then they give you some feedback. So that's the entire process. That's the logical error. The third kind of error is the runtime errors or you can say exceptions. Now exceptions are actually tricky because this is not the problem by the developers right? So they have done everything correct. It's a mistake from the user. Okay. Most of the time because let's say if you are dividing a number by zero as a developer you will not do that. But if you are doing an operation where you're dividing by zero and this input is coming from the user, user can say divide by zero and then it will give you an exception. Second, let's say your app is looking for a file. Okay, so if it has to work, you need to have a file where it stores data and that's in your C drive. When you are developing the application, the file was there and you have never got an error where it says file not found. But now let's say you have given this application to your user and user knows there should be a file in the C drive. Maybe it automatically create that file and everything is working for a few days. One day user got an error by saying you know your C drive is full and then user start deleting some folders or some files and one of the file is the file which your app needs and then user deleted deleted that file and now you're trying to open the app and the app crashes. Not because of developers error, it's a user problem. they have dated that file and when you get error like that your app will crash and you don't want it to happen and that's why you should handle it. Now how will you do that? So basically the concept is exceptions. So let's try to handle the exceptions and to do that what I'm going to do is I'm going to create a new folder and let's say advance because now we are in the next step of Python. So let's say advance and in this let me create a file called exception demo. py and in this let's write code. Now first of all I'm not going to disable my co-pilot for this particular videos because now you know the syntax you know even if AI is helping you helping me to write the code why not okay so let's write some code what I'm expecting here is let's say I got two values one is a and the value of a is five then b the value of b is two and I'm going to do a very simple operation where I'm going to store this operation of divide into a result and then I'm going to print it nothing fancy simple stuff right if I run this so of course I to come out of basics. Let's get into advanced mode and clear. Let's run the Python. So, Python exception demo py enter. And you can see we got the result as 2.5. Everything works. No problem. Happy life. Happy code. Okay. So, let's print one more thing here which is let's say end of program. I was supposed to type by but then copied suggest write end of program. Now why I'm writing this is because when you execute this after of of course your application has so much things to do and let's say that code is here not just enter program let's say we have a lot of code if this executes I'm expecting other thing will also execute okay so if something breaks here this will not execute so if I run this code once again it works and it says end of program or it will say end of execution okay now let's say I make it as zero so if you make the B value zero let's see what happens enter you got an error and there's not a First time we are getting error. But something to observe. First of all, it is giving you the reason on line number five. Because of this operation, you're getting the error. You also have this operation here. It says this is a problem. You know this slash is a problem here. Actually, the slash is not a problem. The problem is B. The value of B is zero. Uh and you can see you are getting a message as well which is division by zero. And observe this zero division error. We'll talk about this later. But let's look at the message which is division by zero. And one thing to observe this message which is end of execution is nowhere that's trouble right because I want it to be there because the app is crashing and I don't want my app to crash. So how do you handle this? Now when you say you want to handle something you can basically look into the statements and decide which of them are critical statements and which of them are normal statements. Now what do you mean by normal statements are critical statements? So let's say if I'm going with my family and I have a kid as well. So let's say we are going to a mall and in there we are we went to a restaurant and we are having our lunch and at this point let's say my kid gots up from the table and just trying to run away somewhere so to a different table which is empty. Will I be panic? Depend upon situation. It's a restaurant. It's a closed restaurant and the next table is empty. So no one's there to get bothered. It's okay if my kid go gets up from my table and goes to the other table, right? Where else he will go? You know, we have a short space there or small space and that's a normal situation for me. But now think about a situation where I'm going to I'm going on a different city and then on the highway I we got a small restaurant or maybe we call Dhaba. I'm waiting there and uh we are having lunch and now the the the open restaurant which we can call it is next to the highway and now my kids get up from the table now that's a panic situation right because we have a highway there the road the vehicles are coming there and that's a critical situation so I will just get panic I will jump and hold his hand right so that's a critical situation so depend upon situation you will try to handle it in this particular code these two statements looks normal to Okay, what will go wrong there? But this line is critical. So what I will do is I will try to handle it and the way you can do that is by writing in a try block. Okay. So this is a try block and this is the code which you want to write in a try block. Now what try block will do is try block will say okay anything inside my block will be handled critically. So it will try to execute this. It will say let me try to execute this statement. If it works that's great. If it doesn't work, I will handle it. But then to handle it, you have to write and you can see if you go here, it says try statement must have at least one except block. So you need to have the except block here. And except block says you have to mention what kind of error you want to handle. Now this is important. So let's say let's go back to that restaurant near to the highway which is open restaurant. Now lot of things can go wrong there, right? One of the thing is my kid gets up from the table. That's critical thing for me. I have to handle it. But there are certain other situation as well. Let's say there is a dish which is getting overcooked. Now that's not my concern. I'm sitting on my table. That's a concern for the chef. Chef need to handle it, right? Or maybe there's something other things that are happening there. Not my concern, right? So I should handle my exceptions. So in this situation, I should be very clear what kind of error I want to handle. So in this case, it is zero division error which we got earlier. So we should handle that. But to understand what other errors we have. So let's go to the Python documentation and let's get into the exception hierarchy. Now if you see here the base exception is the top class exception. Okay when I said top class it's a pun intented in the class hierarchy. It's a topmost class but also the top best doesn't matter. I tried something it doesn't it's not working. But the main point is this exception. This is the main exception for us. So this can handle everything. Now when I say everything what it means it can handle arithmetic error if something goes wrong with your calculation or uh overflow error or there's there's a problem with the floating point and there's also a problem with the zero division. So this zero division is a subclass of arithmetic error. Arithmetic error is a subclass of exception. Okay. Now if you go down there are more errors. Let's say we got buffer error, we got end of file error. Then what are the things we can use? Yeah, file not found error. This is what I was talking about. The file does not exist. and uh recussion error could be one value error which you're going to see later. So there are different kind of errors which comes under exception. So if you get any of any of this exception and if you have exception which can handle it, it can handle it. So what I'm going to do is in our code let's write instead of saying zero division I will write exception. Okay, the main exception and if you click on exception you can see it's a class which is extending or which is inheriting the base exception and base exception is like a topmost class. It is not inheriting everything or anything. So you can get into exception. We also got stop iteration which we might see later. And yeah, so we can see we got arithmetic error which extends or inhite exception inside this. There should be zero divide error. Yeah, zero division error which inhites arithmetic error. So you know now you know the flow right how it is uh doing. But now if you say exception it can handle everything you know. So let's write exception and let's print here something. So let's print here by saying okay I think I made a mistake. An error occurred division by 0 is not allowed. Okay this is what I'm going to write. I think I clicked something because of which I getting this thing. I don't want it. Let's stick to our own the original terminal. Okay. So you got the statements and you're putting that in a try block. That's how thing works, right? So let me just save this and run. And you can see it says an error occurred. Division by zero is not allowed. That's proper. But if you observe it is not crashing the application. You are saying end of the execution. This is important. It is saying end of the ex execution. So that's how basically you handle the try. I mean you handle the statements by putting that in a try block and then you try to handle the exception by using except exception and then you print something. I mean it's not just printing. You can do some operations as well. Maybe you can do this operation again by changing the value of B. You can ask the user, hey, give a new value for the B and then you can do that here and make it work. So you can do whatever you want in the accept block. So that's how you use try and accept. Now let's say you are taking the input from the user. So the the way you can do that is by saying int. You have to also convert that. So let's say input I will say enter a numerator and here enter the denominator. That's perfect. And now let's see if this works. So let me just run this. Enter. Asking for the numerator 4 2. Everything works well. You can see it says result is 2.0. And then end of execution. Perfect. Now let's run this. I will say 4ide by 0. Okay. It says error occurred. That's good. Division by 0. My mistake. And end of execution. App is not crashing. That's great. Let me run this again. Four. And I wanted to type five but then I entered T. When you say enter here you can see we got an error and the app is crashing. How do I know? It is not printing end of execution. Now what went wrong? This line which is B equal to this line is the problem and the error is value error. Remember we talked about value error and I've shown you that in that uh hierarchy it says invalid literal for input because input function try to convert into integer it is trying to convert integer t it's not integer so you can you cannot convert it so this statements also become a critical statement these are not normal statements so I can just pick it up put that in a try block at least it should not crash it now so let's run this okay and run let's say 4 and2 everything works proper. Let's say 4 and zero. Everything works proper. And now let's say four and t. Okay, you can see for t it's not crashing. It says end of execution. But there's something some problem with the error message. It says error occur division by 0 is not allowed. It's not zero. It is t. What is going wrong? See, if something goes wrong with the try block, of course, you will execute the except except block. We only have one except block. It is going here. It is printing this message. Not a good message, right? Because the problem is different. What you can also do is you can print the message here. So you can just say exception E. So whatever exception object which is getting raised, you can put that in E and you can print E here. Okay. Now you will get the error message. So for N and T, you're getting this message because that's what you have written here hardcoded. But look at the E message. It says invalid literal for integer t. Perfect. So that's actually good. But then for 490 we also getting the same message. Not a good style. But yeah this message different. This is same. So if you want to type a different message. Don't you think there should be different except block for different kind of errors. Example, let's say if you want to if you're preparing for a board exam and I remember my school time when you're preparing for the board exam before the exam my school used to arrange this 10 days doubtsolving sessions with your teachers if you get errors let's say for maths we have we have a classroom where we have a math teacher you can go there resolve your doubts we have a teacher for science you can go there and resolve your doubts but there are certain doubts which knowing can answer okay maybe someone is bullying you someone you you you lost your whole pass in that case you will go to your class teacher. So you can be very specific here. So exception you can say this is zero division error and I can just write zde just to differentiate the objects and the message is this and then you can write one more except block which is for the value error and you can write a message like this and then uh this works and then you can have a universal exception where you can say unexpected error occurred. Now for the first two this for this particular Excel block we got this is zero division this is value error now based on which error is arising first it will execute that particular except block okay so if I run this and if I say 4 and t now this time it is not divide by zero error it is the value error and that's why you can see it says an error occurred invalid input please enter numeric values only and that's a proper message right and that's why and since you are printing v again it is printing the message you can skip V now right that make much more sense but let's keep it there for our understanding if it is a 0 divid by error it will print that message so let's say four and zero it will print division by 0 is not allowed right so that's for the zero error so it it will not execute both the moment it gets at least any any one error it will jump to the matching except block okay now I don't see any extra error here but we just wrote this for our safety right if something goes wrong which is not I'm not handling it here except we'll handle it if you can generate any error which is not in this let me know and somewhere in the comments or in the uh notes somewhere for the others to see okay so this is about try with multiple except block now we can talk about try with finally see what happens is when you work with the complex software you work with databases you work with network connections you open files now all these things are actually called resources Right? So database connections are resources, files are resources and it is your responsibility as a developer after using the resource you have to close it. Right? So let's say in this code I'm not using any resources but let's pretend we are using some resource. So I can say resource opened successfully. This can be database connection. This can be a file opening. This can be network connection. Resource opened successfully. And then I have to make sure I I will close it. Now which is a best place to close any exception or any thing. The best place to co to close a connection is a final block. Now final block is a block which will exe which will get executed even if you get the exception or even if you don't get the exception because see the except block will execute only when you get the exception right try block complete executions depend upon if you get the exception or not. If there's no exception it will execute the entire block. If there's exception it will stop the execution into try block and jump to accept. But final block executes irrespective if you get the exception or not. So it's always better to write final block in which you close the resources. So if you run this, let's run three and four. You can see it says resource closed. And even if you get the exception four and zero, it will say resource closed. And even if you crash for some reason, so let's say I'm not handling value here. And let's see what happens. I'm just experimenting it here on this on the go. It says resource opened and it crashed. It crashed. Okay. So, it's not printing end of execution, but it says resource closed. Doesn't matter if it is crashing or not. So, before crashing, it will close the resource. And that's important. So, that's why you should put things in the final block. Perfect. But there's one more important thing with the final block is uh let's say if you don't put final block and try block if you skip that try block will say try statement must have at least one except or a finally clause. Okay. So either you need a except or you need finally. So you can also have a finally here. Maybe you can print something clean resources. So if you want to write try either you need finally or you need except block or you can have both. Just remember that. So yeah, that's it. That's it from the exceptions. I hope it makes sense.

Original Description

In this video, we’ll understand Exception Handling in Python in detail — starting from basic concepts and moving all the way to practical implementation. Here’s what we’ll cover 👇 ▶️ Types of Errors: First, we’ll understand the three main types of errors in Python: i) Syntactical Errors ii) Logical Errors iii) Exceptions We’ll also clearly differentiate between these three types. ▶️ Exception Handling Syntax: We’ll learn the syntax of the try-except block and see how it is used to handle runtime exceptions effectively. ▶️ Exception Hierarchy: We’ll explore Python’s exception hierarchy and understand how exceptions are internally organized. ▶️ Practical Mini Application: We’ll build a small application that covers multiple exception-handling scenarios, helping you understand the concept end-to-end. ▶️ finally Block: Finally, we’ll discuss the finally block and see how it always executes, whether an exception occurs or not, and how it works together with the try block. By the end of this video, you’ll have a complete understanding of Python exception handling — including concepts, syntax, and real-world usage. Check out our courses: Mastering Agentic AI with Java: Spring AI, LangChain4j, MCP & ADK: https://go.telusko.com/agentic-ai Coupon: TELUSKO10 (10% Discount) DevOps Bootcamp: https://go.telusko.com/complete-devops Coupon: TELUSKO10 (10% Discount) Master Java Spring Development : https://go.telusko.com/learn-master Coupon: TELUSKO10 (10% Discount) For More Queries WhatsApp or Call on : +919008963671 website : https://telusko.com/ Instagram : https://www.instagram.com/navinreddyofficial/ Linkedin : https://in.linkedin.com/in/navinreddy20 WhatsApp : https://go.telusko.com/whatsapp TELUSKO Android App : https://go.telusko.com/TELUSKOAPP TELUSKO IOS App : https://apple.co/3SsgmU2 Discord : https://discord.gg/D8hWe9BqfF
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Related AI Lessons

I Let 5 AI Agents Shop For Me in 2026. It Went About as Well as You’d Expect.
Learn from an experiment where 5 AI agents were used to shop for everyday items, highlighting what works and what doesn't in AI-powered shopping
Medium · AI
The Governance Gap Nobody's Measuring
Learn how to identify and address the governance gap in AI systems, where configuration changes can lead to unintended consequences, and why it matters for ensuring accountability and transparency
Medium · AI
My agent kept reading data it wasn't allowed to. The prompt was never going to stop it.
Learn how to secure autonomous agents with proper credential management to prevent unauthorized data access
Dev.to AI
8 Must-Know AI Chatbot Tools That Actually Help Small Businesses
Discover 8 essential AI chatbot tools that can genuinely benefit small businesses, and learn how to choose the right one for your specific use case
Dev.to AI
Up next
Building Great Agent Skills: The Missing Manual
AI Engineer
Watch →