Python Print Exception
Last Updated :
27 Nov, 2023
An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting. In this article, we are going to focus on ‘How can we print an exception in Python?’
What is Exception in Python?
In Python, Exception is a type of Error in the program. An Error is called an ‘Exception’ when the program is syntactically correct, but an error occurs while executing it.
Example: In the example, we are trying to divide a number by zero so it gives a runtime error.
Python3
num1 = 5
num2 = 0
print (num1 / num2)
|
Output
Traceback (most recent call last):
File "Solution.py", line 5, in <module>
print(num1 / num2)
ZeroDivisionError: division by zero
This program is syntactically correct. The only problem here is due to the numbers that are used for the operation. Since we cannot divide any number by 0, it throws an error. Thus, this is an example of ‘Exception’.
What do Exceptions look like?
In the above program, when we executed it, we got an exception. The error that was thrown, showed the line at which the error occurred, the exact line, and the Error Type.
The Error Type that was shown is called the ‘Exception’. Through Exceptions, we come to know about the problem that has occurred. The Exception in the above program is “ZeroDivisionError: division by zero“.
Example: Here, the assignment of the variable var1 is done by an undefined variable, var2.
Output
Traceback (most recent call last):
File "Solution.py", line 2, in <module>
var1 = var2
NameError: name 'var2' is not defined
Above, we can see the Exception as “NameError: name ‘var2’ is not defined“.
Exception Handling in Python
Exceptions can be very bothering at times. Here’s where the concept of Exception Handling comes in. Through Exception Handling, we can easily handle the exceptions for the user instead of just throwing errors at the user.
Example : In this program, the input is taken in the type ‘int’. But if we enter a character in it, it will throw a ‘ValueError’. This can confuse the user a lot of times. Here’s where we do the Exception Handling. Instead of throwing value error and confuse the user, we will display a statement suggesting the user to try again and we will give a chance to the user to try inputting the numbers again.
Python3
num1 = int ( input ( 'Enter num1: ' ))
num2 = int ( input ( 'Enter num2: ' ))
answer = f '{num1} / {num2} = {num1 / num2}'
print (answer)
|
Output
Enter num1: 1
Enter num2: b
Traceback (most recent call last):
File "D:/PycharmProjects/pythonProject2/main.py", line 15, in <module>
num2 = int(input('Enter num2: '))
ValueError: invalid literal for int() with base 10: 'b'
Using try, except and else
In this code, the while loop is run because we want to let the user try until the input is given in the correct way.We have used the ‘try’ clause. The try clause checks for the errors in the lines in that clause.
If an exception is encountered, it jumps to the ‘except’ clause and prints the error message provided by us. We have written two except clauses, one with the ValueError and the other with the ZeroDivisionError. Each of these clauses deal with respective exceptions and print out the respective messages.
Then, lastly, we have written the else clause. If no error is encountered, the else block is executed. In the else block, we print the quotient of the division and break out from the loop.
Python3
while True :
try :
num1 = int ( input ( 'Enter num1: ' ))
num2 = int ( input ( 'Enter num2: ' ))
answer = f '{num1} / {num2} = {num1 / num2}'
except ValueError as e:
print ( 'Try putting an integer value.\n Error Occured:' , e)
except ZeroDivisionError as ex:
print ( 'Division by zero is invalid!\n Error Occured:' , ex)
else :
print (answer)
break
|
Output:
Printing Exceptions
Now, as we have seen what exceptions exactly are, how do they look like and how to handle them, we will now have a look at printing them.
To print the Exceptions, we use ‘as’ keyword of Python.
We have used the same example that we used before. We have used the ‘as’ keyword and declared the variable ‘ve’ for ‘ValueError’ and ‘zde’ for ‘ZeroDivisionError’. Then, if we encounter any exceptions, we have written the code to print that exception. But still, we are not able to see the Type of Exception we got.
Python3
while True :
try :
num1 = int ( input ( 'Enter num1: ' ))
num2 = int ( input ( 'Enter num2: ' ))
answer = f '{num1} / {num2} = {num1 / num2}'
except ValueError as ve:
print (ve)
except ZeroDivisionError as zde:
print (zde)
else :
print (answer)
break
|
Output:
Enter num1: a
invalid literal for int() with base 10: 'a'
Enter num1: 0
Enter num2: 0
division by zero
Enter num1: 16
Enter num2: 4
16 / 4 = 4.0
Printing Exception Type
To see the exception type, we can use the type() function.
Here we have used the type() function to know the type of exception we have encountered while running the code.
Python3
while True :
try :
num1 = int ( input ( 'Enter num1: ' ))
num2 = int ( input ( 'Enter num2: ' ))
answer = f '{num1} / {num2} = {num1 / num2}'
except ValueError as ve:
print ( type (ve), ve)
except ZeroDivisionError as zde:
print ( type (zde), zde)
else :
print (answer)
break
|
Output
Enter num1: a
<class 'ValueError'> invalid literal for int() with base 10: 'a'
Enter num1: 1
Enter num2: 0
<class 'ZeroDivisionError'> division by zero
Enter num1: 4
Enter num2: 2
4 / 2 = 2.0
Please Login to comment...