Skip to content

Latest commit

 

History

History
210 lines (147 loc) · 4.37 KB

README.md

File metadata and controls

210 lines (147 loc) · 4.37 KB

Chapter 9: Exception Handling

Table of Contents

Introduction to Exceptions

An exception is an error that occurs during the execution of a program. When an exception occurs, the normal flow of the program is disrupted, and the program terminates abnormally. Exception handling is a mechanism to handle runtime errors, ensuring the program continues to run smoothly.

Example: Unhandled Exception

print(x)

Output:

NameError: name 'x' is not defined

Explanation: The above code raises a NameError because the variable x is not defined.

Handling Exceptions with try and except

The try block lets you test a block of code for errors. The except block lets you handle the error.

Basic try-except

try:
    print(x)
except NameError:
    print("Variable x is not defined")

Output:

Variable x is not defined

Explanation: The try block contains code that might raise an exception. The except block contains code that runs if an exception occurs.

Handling Multiple Exceptions

try:
    n = int(input("Enter a number: "))
    print(n)
except ValueError:
    print("Please enter a valid integer")
except NameError:
    print("Variable is not defined")

Output:

Enter a number: abc
Please enter a valid integer

Explanation: The code handles both ValueError and NameError exceptions.

Example: Division by Zero

a = [0, 1, 3, 5, 10]
x = 20

for i in a:
    try:
        print(x / i)
    except ZeroDivisionError:
        print("Division by zero is not allowed")

Output:

Division by zero is not allowed
20.0
6.666666666666667
4.0
2.0

Explanation: The code handles the ZeroDivisionError exception when dividing by zero.

The else and finally Clauses

The else block lets you execute code if no exceptions were raised. The finally block lets you execute code regardless of whether an exception was raised or not.

Using else

a = [1]
x = 20

for i in a:
    try:
        print(x / i)
    except ZeroDivisionError as e:
        print(e)
    else:
        print("Success")

Output:

20.0
Success

Explanation: The else block runs if no exceptions were raised in the try block.

Using finally

a = [1]
x = 20

for i in a:
    try:
        print(x / i)
    except ZeroDivisionError as e:
        print(e)
    finally:
        print("End")

Output:

20.0
End

Explanation: The finally block runs regardless of whether an exception was raised or not.

Raising Exceptions

You can raise an exception using the raise keyword.

Example: Raising an Exception

x = '10'

if type(x) is not int:
    raise TypeError('Only integers are acceptable')

Output:

TypeError: Only integers are acceptable

Explanation: The code raises a TypeError if x is not an integer.

Creating Custom Exceptions

You can create custom exceptions by defining a new class that inherits from the built-in Exception class.

Example: Custom Exception

class CustomError(Exception):
    def __init__(self, message):
        self.message = message

try:
    raise CustomError("This is a custom error")
except CustomError as e:
    print(e.message)

Output:

This is a custom error

Explanation: The CustomError class inherits from the Exception class. The code raises a CustomError and handles it in the except block.

Summary

In this chapter, we covered exception handling, including the try and except blocks, the else and finally clauses, raising exceptions, and creating custom exceptions.

Tasks

  1. Write a program that handles a ZeroDivisionError when dividing two numbers.
  2. Write a program that handles multiple exceptions, such as ValueError and TypeError.
  3. Write a program that uses the else and finally clauses in exception handling.
  4. Write a program that raises a custom exception if a condition is not met.
  5. Create a custom exception class and use it in a program.

Next Chapter: Conclusion and Further Learning