Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Exception Groups in Python
Next article icon

Python Print Exception

Last Updated : 12 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, exceptions are errors that occur at runtime and can crash your program if not handled. While catching exceptions is important, printing them helps us understand what went wrong and where. In this article, we'll focus on different ways to print exceptions.

Using as keyword

as keyword lets us store the exception in a variable so you can access its message. We catch a specific error like ValueError or ZeroDivisionError and print the message directly. This is the most common and beginner-friendly way to print exceptions. It keeps the output clean and easy to understand.

Python
try:     num = int(input("Enter a number: "))     print(10 / num)  except ValueError as ve:     print("ValueError:", ve)  except ZeroDivisionError as zde:     print("ZeroDivisionError:", zde) 

Output

Enter a number: gfg 
ValueError: invalid literal for int() with base 10: 'gfg'

Explanation: This code asks the user for a number, converts it to an integer and divides 10 by it. If the input isn't a valid integer, a ValueError is printed. If the input is 0, a ZeroDivisionError occurs since division by zero isn’t allowed and that error message is printed.

Using type()

This method helps us print the type of exception you caught, like <class 'ValueError'>. It's useful when we're not sure what kind of error occurred. Along with type(e), we can also print e to get the actual error message. It’s handy for debugging or logging detailed error types.

Python
try:     num = int("text")  except ValueError as e:     print("Type of Exception:", type(e))     print("Message:", e) 

Output
Type of Exception: <class 'ValueError'> Message: invalid literal for int() with base 10: 'text' 

Explanation: This code tries to convert the string "text" into an integer, which isn’t possible and raises a ValueError. The except block catches the error, prints its type using type(e) and displays the error message using e.

Using traceback.print_exc()

The traceback module prints the full traceback of the exception. It shows the exact line of code and function call that caused the error. Very useful when you're debugging large programs or need detailed logs. Make sure to import traceback before using it.

Python
import traceback  try:     res = 10 / 0  except ZeroDivisionError as e:     print("Traceback Info:")     traceback.print_exc() 

Output

Traceback Info: 
Traceback (most recent call last):
File "<ipython-input-36-a96b18b23dc7>", line 4, in <cell line: 0>
res = 10 / 0
~~~^~~
ZeroDivisionError: division by zero

Explanation: This code tries to divide 10 by 0, which raises a ZeroDivisionError. The except block catches the error and uses traceback.print_exc() to print a detailed traceback, showing where the error occurred in the code.

Using str() and repr()

str() returns a user-friendly version of the exception message and repr() gives a more detailed and developer-focused representation of the error. Using both can help differentiate between readable output and debug-level logs. This method is useful when you want more control over how the exception is displayed.

Python
try:     int("not_a_number")  except ValueError as e:     print("str():", str(e))     print("repr():", repr(e)) 

Output
str(): invalid literal for int() with base 10: 'not_a_number' repr(): ValueError("invalid literal for int() with base 10: 'not_a_number'") 

Explanation: This code tries to convert the string "not_a_number" into an integer, which raises a ValueError. The except block catches the error and prints the message using str(e) for a readable format and repr(e) to show the official string representation, which includes the exception type and message.


Next Article
Exception Groups in Python

S

sarajadhav12052009
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Geeks Premier League 2023
Practice Tags :
  • python

Similar Reads

  • Exception Groups in Python
    In this article, we will see how we can use the latest feature of Python 3.11, Exception Groups. To use ExceptionGroup you must be familiar with Exception Handling in Python. As the name itself suggests, it is a collection/group of different kinds of Exception. Without creating Multiple Exceptions w
    4 min read
  • Python Exception Handling
    Python Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example: Hand
    7 min read
  • Python Built-in Exceptions
    In Python, exceptions are events that can alter the flow of control in a program. These errors can arise during program execution and need to be handled appropriately. Python provides a set of built-in exceptions, each meant to signal a particular type of error. We can catch exceptions using try and
    9 min read
  • Concrete Exceptions in Python
    In Python, exceptions are a way of handling errors that occur during the execution of the program. When an error occurs Python raises an exception that can be caught and handled by the programmer to prevent the program from crashing. In this article, we will see about concrete exceptions in Python i
    3 min read
  • Errors and Exceptions in Python
    Errors are problems in a program that causes the program to stop its execution. On the other hand, exceptions are raised when some internal events change the program's normal flow. Syntax Errors in PythonSyntax error occurs when the code doesn't follow Python's rules, like using incorrect grammar in
    3 min read
  • __exit__ in Python
    Context manager is used for managing resources used by the program. After completion of usage, we have to release memory and terminate connections between files. If they are not released then it will lead to resource leakage and may cause the system to either slow down or crash. Even if we do not re
    3 min read
  • EAFP Principle in Python
    EAFP is a piece of gem advice in the Python community which may not be familiar to programmers of other communities. Quickly, EAFP or 'Easier to Ask for Forgiveness than Permission' means holding an optimistic view for the code you are working on, and if an exception is thrown catch it and deal with
    2 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
    3 min read
  • Python Naming Conventions
    Python, known for its simplicity and readability, places a strong emphasis on writing clean and maintainable code. One of the key aspects contributing to this readability is adhering to Python Naming Conventions. In this article, we'll delve into the specifics of Python Naming Conventions, covering
    4 min read
  • Python Try Except
    In Python, errors and exceptions can interrupt the execution of program. Python provides try and except blocks to handle situations like this. In case an error occurs in try-block, Python stops executing try block and jumps to exception block. These blocks let you handle the errors without crashing
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences