Error Handling: Try and Except in Python (2023) - Error Handling Tutorial

Akansha Yadav shows how try and except blocks catch errors in Python. She builds a program that divides 10 by user input, handling both division by zero and non-numeric entries without crashing.
Chapters
In today's video, we will discuss about try and except in Python. So basically, this is a part of exception handling. Exception handling, as the name says, it handles the exceptions, some errors. So in try block— try block is basically the block in which you are going to write down your code where exception might occur. So if the exception is there, then it will jump on to the except block, and except block is the one which handles the exception. So in except block, we will be specifying the type of exception whether it is ValueError, AttributeError, NameError, or which type of error is going to occur and how to tackle those errors. So we will be writing the corresponding actions as well, which will allow our program to continue without any crashes. So let's write down a program onto the same. On my screen you can see try and except definition as well. So let's write down the code. So here I am writing try x input. I am taking of a number, then I am trying to divide it by the number that I am going to take. I am going to divide 10 by that number. Then I am printing the result. If result gives us ZeroDivisionError, which says that value cannot be divided by 0, it means 10 cannot be divided by 0. In that case, it will handle those exception. And another error that I am presenting is the ValueError. If there is any ValueError, then also it can handle. So I am entering, let's suppose I am entering 2. It is easily divisible by 10, so 10 divided by 2 is 5.0. Now this time I am going to write 0. Now this time we are getting an error, division by 0 is not allowed. Now running the file again, trying to write any character over here just to check whether ValueError is tackled or not. So yes, it is.










