0
0
Pythonprogramming~5 mins

Why exceptions occur in Python

Choose your learning style9 modes available
Introduction

Exceptions happen when something unexpected goes wrong while a program runs. They stop the normal flow so the problem can be fixed or handled.

When reading a file that might not exist.
When dividing numbers and the divisor could be zero.
When converting user input to a number but the input might be wrong.
When accessing a list item that might be out of range.
Syntax
Python
try:
    # code that might cause an error
except SomeError:
    # code to handle the error

The try block contains code that might cause an error.

The except block runs if an error happens in the try block.

Examples
This catches the error when dividing by zero and prints a message.
Python
try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
This handles the case when the user types something that is not a number.
Python
try:
    num = int(input("Enter a number: "))
except ValueError:
    print("That is not a valid number.")
Sample Program

This program tries to access a list item that is not there. It catches the error and prints a friendly message.

Python
try:
    numbers = [1, 2, 3]
    print(numbers[5])
except IndexError:
    print("Oops! That index does not exist.")
OutputSuccess
Important Notes

Exceptions help keep programs from crashing suddenly.

Always try to handle exceptions you expect to happen.

Use specific exception types to catch only the errors you want.

Summary

Exceptions happen when something unexpected goes wrong in the program.

Use try and except to catch and handle these errors.

Handling exceptions makes programs more reliable and user-friendly.