Programming is not a one day or one week syllabus to learn and start coding. To become proficient in it, consistent practice, handling errors, manage codes and staying up-to-date the latest programming knowledge are essential.
When we start learning then we know that mistakes are common and indeed, every beginner learns through them.
In Python, "exception handling" refers to the process of addressing errors that arise while excuting the codes. This is a very important for any coder because if we don't pay attention on it, we will not able to expert in Programming.
What is Exception?
In Python, an exception is an event that disrupts the normal flow of execution. It is also referred to as a runtime error.
Example of Error
num1 = int(input("Enter a Number to Divide 10: ")
print(10/num1)
This code works fine until a user didn't type ' 0 ' or string like 'abc'. To solve this issue we have "try" and "except" keywords.
What is Keywords?
Keywords are the reserve words that we cannot use them as variable name, function or identifiers. All these have special meaning like if, else, class, def, return, etc.
What is Try and Except?
"Try" and "Except" is designed to handle error gracefully so that code will run normally. "Try" run a block of code and if it fails with an error, the "except" block runs instead.
Syntax
try:
# code that may cause error
except:
# code to handle error
Example of Handling Error
try:
num1 = int(input("Enter a Number to Divide 10: "))
print(10/num1)
except:
print("This is an invalid) By looking at the image, you can understand how the code executes after using "try" and "except".
Handling Specific Exception
Now if we want to handle this error in boarder way or in a meaningful way, then we can use specific errors.
Example of Handling Error
try:
num1 = int(input("Enter a Number to Divide 10: "))
print(10/num1)
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("You cannot divide by Zero") ValueError and ZeroDivisionError are the built-in python class to define error.
Use Else
If we want to run a block of code when no error occurs then we can use "else".
Example of Handling Error
try:
num1 = int(input("Enter a Number to Divide 10: "))
result = (10/num1)
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("You cannot divide by Zero")
else:
print("Result is: ",result) V
