Open In App

Python Print Exception

Last Updated : 27 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




var1 = 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:

Screenshot-from-2023-10-16-12-36-50

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



Similar Reads

Python | Raising an Exception to Another Exception
Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information about both errors. Code #1 : def example(): try: in
2 min read
How to print exception stack trace in Python?
Prerequisite: Python Traceback To print stack trace for an exception the suspicious code will be kept in the try block and except block will be employed to handle the exception generated. Here we will be printing the stack trace to handle the exception generated. The printing stack trace for an exception helps in understanding the error and what we
3 min read
How to print the Python Exception/Error Hierarchy?
Before Printing the Error Hierarchy let's understand what an Exception really is? Exceptions occur even if our code is syntactically correct, however, while executing they throw an error. They are not unconditionally fatal, errors which we get while executing are called Exceptions. There are many Built-in Exceptions in Python let's try to print the
3 min read
Multiple Exception Handling in Python
Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages. If you can handle different exceptions all using a single block of code, they can be grouped together in a tuple as shown in th
3 min read
Python | Reraise the Last Exception and Issue Warning
Problem - Reraising the exception, that has been caught in the except block. Code #1: Using raise statement all by itself. def example(): try: int('N/A') except ValueError: print(&quot;Didn't work&quot;) raise example() Output : Didn't work Traceback (most recent call last): File "", line 1, in File "", line 3, in example ValueError: invalid litera
2 min read
Create an Exception Logging Decorator in Python
Prerequisites: Decorators in Python, Logging in Python Logging helps you to keep track of the program/application you run. It stores the outputs/errors/messages/exceptions anything you want to store. Program executions can be debugged with the help of print statements during the runtime of code. But the code is not elegant and not a good practice.
2 min read
How to pass argument to an Exception in Python?
There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the following reasons: It can be used to gain additional
2 min read
Test if a function throws an exception in Python
The unittest unit testing framework is used to validate that the code performs as designed. To achieve this, unittest supports some important methods in an object-oriented way: test fixturetest casetest suitetest runner A deeper insight for the above terms can be gained from https://www.geeksforgeeks.org/unit-testing-python-unittest/ assertRaises()
4 min read
Handling TypeError Exception in Python
TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise a TypeError. ExamplesThe general causes for TypeError being raised are: 1. Unsupported Operation Betwe
3 min read
EnvironmentError Exception in Python
EnvironmentError is the base class for errors that come from outside of Python (the operating system, file system, etc.). It is the parent class for IOError and OSError exceptions. exception IOError - It is raised when an I/O operation (when a method of a file object ) fails. e.g "File not found" or "Disk Full".exception OSError - It is raised when
1 min read
three90RightbarBannerImg