Errors and exceptions in Python
An exception ( Exception ) is an unexpected event that occurs during the normal flow of program execution. Also known as runtime error. When this error occurs, Python generates an exception during execution that can be handled, preventing your program from stopping. We can say that an exception in Python is a response to exceptional circumstances that arise during the operation of the program.
In this article, we will discuss how to handle exceptions in Python using try and exception.
There are two types of errors in Python:
1- Error in syntax or wording of the programming sentence. It is the most common type of error.
Examples of programming errors in syntax and writing
example:
while True print('You're welcome')
The output will be:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python3.8/py_compile.py", line 150, in compile
raise py_exc
py_compile.PyCompileError: File "./prog.py", line 1
while True print('You're welcome')
^
SyntaxError: invalid syntax
The error occurred here while writing the code. The error was detected in the print() function, because a colon (':') was missing before it.
Note: The file name and line number in which the error is located are printed.
Example:
price=undefined 500
if(price > 1000)
print("You qualify for free shipping")
The output will be:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python3.8/py_compile.py", line 150, in compile
raise py_exc
py_compile.PyCompileError: File "./prog.py", line 1
price=undefined 500
^
SyntaxError: invalid syntax
The error occurred here while writing the code. The error was discovered in an 'if' statement, which must be followed by a colon (':').
Also there is an error in the indentation of the print() function. It must be indented before it.
2- Error exceptions. It occurs when the code is executed
Exception errors appear even if the code or sentence is written grammatically correctly but the code produces an error during its execution.
example:
marks = 10 * (1/0)
The output will be:
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
ZeroDivisionError: division by zero
This error is called ZeroDivisionError and it occurs when we divide a number by zero.
example:
x = 'hello' + 2
The output will be:
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
This error is called TypeError and it occurs when we try to perform a mathematical operation, for example (add or subtract a number) with a text string.
How to handle exceptions in Python.
Try and except statements are used to handle exceptions. Where the code that is likely to be excluded is written inside the try block
The programming statement or code that deals with the exception is written inside the except block.
example:
while True:
try:
age = int(input("Please enter a number:"))
break
except:
print("This was not a valid number. Try again...")
In the previous example, we placed the code that is likely to be excluded inside the try block. Here, it means entering a number into the age field. If the user enters any value that does not represent a number. A text string, for example. The code inside the try block is skipped and the code inside the except block is then executed.
How to implement a specific type of exception in undefined Python.
If an exception occurs while executing the try statement, the rest of the statement is skipped. Then, if its type matches the exception named after the except keyword, the exception statement is executed,
example:
try:
print(ahmed)
except NameError:
print("The variable ahmed is not defined")
except:
print("An error occurred")
The output will be:
The variable ahmed is not defined
In the previous example we specified the exception type which is NameError.
Using multiple exceptions in Python
Here is an example that shows how to use multiple exceptions:
try:
num = int(input("Enter a number:"))
result = 5 /num
except ZeroDivisionError:
print("You cannot divide by zero.")
except ValueError:
print("Invalid entry. Please enter a valid number.")
except Exception as e:
print(f"An error occurred: {e}")
In the previous example, we used multiple exceptions: Exception, ValueError, and ZeroDivisionError
Using finally and else in the exception block in Python.
First: else: if the try clause does not throw any exception. Only the else block is executed. That is, it will be implemented undefined Else block only if no exception occurs.
example:
#Python code to demonstrate the operation of try
try:
print("Enter your name")
except:
print("Enter your name")
else:
print("No error occurred")
The output will be:
Enter your name
Nothing went wrong
Finally: There may be some situations where the current function terminates while handling some exceptions. But the function may require some additional steps before it terminates, such as closing a file, network, etc. So, in order to handle these situations, Python provides the finally keyword, which is always executed after try and except blocks.
example:
try:
x = open("pathfile.txt")
try:
x.write("Lorum Ipsum")
except:
print("An error occurred while writing to the file")
finally:
x.close()
except:
print("An error occurred when opening the file")
The output will be:
An error occurred when opening the file
In the previous example we tried to open a file that was not writable. The finally statement closed the file and terminated the program, thus raising the exception (an error occurred when opening the file).
Tags
python-exception
Share page
About author
Ahmed Obaid
Hello, I am Ahmed Obaid, an Egyptian Arabic programmer. I would like to put my experiences learning Python on this site So that it will be a reference for you and me as well.
Sign up to leave a comment