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.
Python3
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)