Python Exception Handling
What is Exception Handling in Python? Well, before we get you started on Exception Handling in Python, let’s learn about it from the beginning. It is obvious for a developer to encounter a few errors or mistakes in their code file. But what if developers could minimize these errors? Wouldn’t it be great? There are exception handling in Python methods, which help developers deal with potential errors and mistakes. I hope by now you have understood what is exception handling in python.
Lets see all the topics we will be covering in this module:
- What Is an Error in Python?
- Exception Handling in Python
- Conflicts in Python Exception Handling
So, without further delay, let’s get started.
What Is an Error in Python?
Before discussing on how to deal with errors, let us try and understand what errors are in Python. Errors are nothing but mistakes in the code which are potentially harmful.
There are two types of errors in Python:
- Syntax Errors
Go for this in-depth job-oriented Python Training in Hyderabad now!
Python Syntax Errors occur while writing the code structure.
test = [1,2,3] test = [1,2,3] for i in test: print(i) Output: File “”, line 3 print(i) ^ IndentationError: expected an indented block
Exception in Python
Exception in Python is nothing but errors which are encountered at the run time.
test = [1,2,3] for i in test: print(i) Output: File “”, line 3 print(i) ^ Indentation Error: expected an indented block
Some Built in Exception in Python Classes
There are some built in exception in Python classes that are already defined for generic cases. They are mentioned in the table below:
|IOError||It gets raised when an input/output operation fails.|
|Arithmetic Error||It gets raised when numeric calculations fail.|
|Floating-point Error||It gets raised when a floating-point calculation fails.|
|Zero Division Error||It gets raised when division or modulo by zero takes place for all numeric types.|
|Assertion Error||It gets raised when the assert statement fails.|
|Overflow Error||It gets raised when the result of an arithmetic operation is too large to be represented.|
|Import Error||It gets raised when the imported module is not found.|
|Index Error||It gets raised when the index of a sequence is out of range.|
|Keyboard Interrupt Error||It gets raised when the user interrupts program execution, usually by pressing (Ctrl+C).|
|Indentation Error||It gets raised when there is an incorrect indentation.|
|Syntax Error||It gets raised by the parser when a syntax error is encountered.|
|Key Error||It gets raised when the specified key is not found in the dictionary.|
|Name Error||It gets raised when an identifier is not found in the local or global namespace.|
|Type Error||It gets raised when a function or operation is applied to an object of an incorrect type.|
|Value Error||It gets raised when a function gets an argument of the correct type but of an improper value.|
|Runtime Error||It gets raised when a generated error does not fall into any category.|
We have the perfect professional Python Course in Bangalore for you!
Exception Handling In Python
In Python, exceptions can be handled by two new methods:
- Try: Catches exceptions raised by Python or a program
- Raise: A custom exception which triggers an exception manually
It gets initiated with a try header line which is followed by a block of indented statements and then by one or more optional except clauses and then at the end an optional else clause can be used as shown below:
try: Your statements except Exception_1: If there is Exception_1 then execute this block- statement except Exception_2: If there is Exception_2 then execute this block-statement else: if no exception was raised-statement
Now, let us understand this with an example:
try: fp = open(‘myfile.txt’) line = f.readline() i = int(s.strip()) except (IOError,ValueError) as e: print (“check if the file is read-only.”,e.errno) except: print (“Unexpected error”)
What exactly is happening here?
Say, a chunk of code is written inside the try block that is suspected to raise a Python exception. Then, to handle that exception, we write the exception block.
First, the try blockis executed
- Case 1:If no Python exception occurs, except blocks are skipped and the else block gets executed
- Case 2:If a Python exception occurs during the execution of the try block, the rest of the execution is stopped. Then, a matching Python exception handling block is looked for.
- If found:Execute that exception block, and after the exception in Python is handled, execute the rest of the try block
- If not found:Stop the whole execution with an error message
Note: Python can handle any number of exceptions.
Looking for Python for Data Science Course All-in-1 Combo Training? Enroll now!
When a final clause is used in a try block, then its block of statements is always run by Python, whether an exception occurred while the try block was running or not:
- If no exception occurs, Python runs the try block and the finally block and then continues executing the rest.
- If an exception in Python0020occurs during execution of the try block, Python starts executing the finally block but then propagates the execution to the except block to handle the exception.
try: fp = open(“test.txt”, “w”) try: fp.write(“Test is not there”) finally: print (“So, let us close the file”) fp.close() except IOError: print (“Error: File not found” ) Output: So, let us close the file
Here, we can notice that the exception block is not executed. This is because the file gets closed after the execution of the finally block.
Raise Exceptions Python
To trigger exceptions, we need to code raise statements. Their general form is simple: the keyword, ‘raise’, followed by the name of the exception to be raised.
class RaisingValueError(Exception): def __init__(self, data): self.data = data def __str__(self): return repr(self.data)Total_movie = int(input(“Enter Total Movies Seen: “)) try: Num_of_genres = int(input(“Enter Num of genres: “)) if(Num_of_genres < 1): raise RaisingValueError(“Number of genres can’t be less than 1”) except RaisingValueError as e: print (“Try entering again:”, e.data)
Conflicts in Python Exception Handling
Yes, it does make our codes robust and secures from potential errors, but exception handling in Python has a side effect too.
There are two types of errors in Python:
- When programs using try-except to handle exception in Python run slightly slower
- When the size of our code increases
Therefore, we should use exception in Python only when we are unsure of certain part of the code, not for normal error handling cases. This can be understood with the help of an example.
import timeit setup=”any=0″ statement_1 = ”’\ try: b=10/a except ZeroDivisionError: pass”’ satement_2 = ”’\ if any !=0: b=10/a”’ print(“time for statement_1=”,timeit.timeit(stmt1,setup,number=100000)) print(“time for statement_2=”,timeit.timeit(stmt2,setup,number=100000)) Output: time= 0.07828223999999295 time= 0.0019908266666845975
This brings us to the end of this module in Python Tutorial. Now, if you want to know why Python is the most preferred language for data science, you can go through this blog on Python for Data Science.Previous Next