Exception Handling in Python

Python tutorial · PySpark.in

Introduction

When a program encounters an error, it usually stops execution and shows an error message. These errors are called exceptions. Python provides a way to handle exceptions gracefully using exception handling, which helps your program continue running even if an error occurs. An exception is an event that occurs during the execution of a program that disrupts the normal flow.

Example of an Exception

```

print(10 / 0) # This will raise a ZeroDivisionError

```

Why Exception Handling is Important

Basic Exception Handling

Python uses try and except blocks to handle exceptions:

```

try:

num = int(input("Enter a number: "))

result = 10 / num

print("Result:", result)

except ZeroDivisionError:

print("Error: Cannot divide by zero!")

except ValueError:

print("Error: Invalid input! Please enter a number.")

```

Explaination

Common Python Exceptions

Exception Type

Description

Example

ZeroDivisionError

Division by zero

10 / 0

ValueError

Invalid value

int("abc")

TypeError

Operation on incompatible types

"5" + 5

IndexError

Index out of range

arr[5]

KeyError

Dictionary key not found

dict["age"]

FileNotFoundError

File does not exist

open("data.txt")

The else and finally Blocks

```

try:

num = int(input("Enter a number: "))

result = 10 / num

except ZeroDivisionError:

print("Cannot divide by zero!")

else:

print("Division successful, result:", result)

finally:

print("Program execution finished.")

```

Handling Multiple Exceptions Together

You can catch multiple exceptions in one line:

```

try:

x = int(input("Enter a number: "))

print(10 / x)

except (ZeroDivisionError, ValueError) as e:

print("An error occurred:", e)

```

Nested Try-Except

You can nest try-except blocks for more control:

```

try:

num = int(input("Enter a number: "))

try:

result = 10 / num

except ZeroDivisionError:

print("Cannot divide by zero!")

except ValueError:

print("Invalid input!")

```

Example: File Handling

Exception handling is very useful when working with files:

```

try:

file = open("data.txt", "r")

content = file.read()

print(content)

except FileNotFoundError:

print("File not found!")

finally:

print("Closing the file...")

try:

file.close()

except NameError:

print("File was not opened.")

```

Raising Exceptions

You can manually raise exceptions using the raise keyword:

```

age = int(input("Enter your age: "))

if age < 18:

raise ValueError("Sorry, you must be at least 18 years old.")

```

Effective Exception Handling

  1. Catch specific exceptions, not all (except Exception is a last resort).
  2. Always use finally to release resources like files,database or network connections.
  3. Provide helpful error messages for users.
  4. Use raise for custom validation rules in your programs.
  5. Handle only specific exceptions, not all errors.

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges