MyInternships.in

Python Files & Errors

Python Exceptions

An exception is what Python creates when something goes wrong while your program runs — like dividing by zero or accessing a missing dictionary key. Understanding them is the first step to writing programs that fail gracefully instead of crashing.


What Is an Exception?

When Python hits a problem it cannot continue past, it "raises" an exception: a special object describing what went wrong. If nothing in your code handles it, the program stops immediately and Python prints a traceback showing exactly where the error happened.

An unhandled exception
Python
numbers = [10, 20, 30]
print(numbers[5])
Output
Output
Traceback (most recent call last):
  File "app.py", line 2, in <module>
    print(numbers[5])
IndexError: list index out of range

Reading a Traceback

A traceback reads bottom to top for the important parts. The last line names the exception type and message (IndexError: list index out of range). The lines above it show the exact file and line number where the failure occurred, which is your first clue for debugging.

💡

Do not panic at a wall of red text. Scroll to the last line first — it tells you the exception type and the actual problem in plain words.

Common Built-in Exceptions

Python ships with dozens of built-in exception types, each describing a specific category of failure. Recognising the common ones by name makes debugging much faster.

ExceptionRaised When
ValueErrorA value has the right type but an invalid value, e.g. int("abc")
TypeErrorAn operation is used on the wrong data type, e.g. "2" + 2
IndexErrorA list/tuple index is out of range
KeyErrorA dictionary key does not exist
NameErrorA variable is used before it is defined
ZeroDivisionErrorDividing a number by zero
FileNotFoundErrorOpening a file that does not exist in read mode
AttributeErrorCalling a method/attribute that does not exist on an object
A few common exceptions
Python
int("hello")        # ValueError
"2" + 2              # TypeError
{"a": 1}["b"]        # KeyError
10 / 0               # ZeroDivisionError

Every exception in Python is an object, and they all trace back to a common ancestor class called Exception. This is important later when you write try/except blocks or design your own custom exceptions, because you can catch a broad category or a very specific one.

ℹ️

Exceptions are not always bugs — they are a normal, expected way for a program to signal "this specific thing went wrong here."

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships