Ad Code

Responsive Advertisement

Basic Python Program - 56

Question 56: Write a Python program to Check for ZeroDivisionError Exception.
Download hole Program / Project code, by clicking following link:
State Exception in Python ?
In Python, an exception is an event that occurs during the execution of a program, causing the program to terminate or change its normal flow. Exceptions are used to handle errors and unexpected situations that may arise while a program is running. They allow you to gracefully respond to and recover from errors rather than having the program crash.

Commonly, exceptions can be categorized into two main types:
  1. Built-in Exceptions: Python provides a wide range of built-in exceptions that cover various types of errors. Some common built-in exceptions include SyntaxError, ZeroDivisionError, NameError, and FileNotFoundError.
  2. User-Defined Exceptions: You can create your own custom exceptions by defining new exception classes that inherit from the base Exception class or its subclasses. This allows you to handle application-specific errors.
Here's a simple example of how exceptions are used in Python:
try:
     # Code that may raise an exception
     num = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
     # Handle the specific exception
     print("Division by zero is not allowed.")
except Exception as e:
     # Handle other exceptions
     print(f"An error occurred: {e}")
else:
     # Code to execute if no exception is raised
     print("Division was successful.")
finally:
     # Code to execute regardless of whether an exception was raised
     print("The program has finished.")

In this example:
  1. We attempt to divide by zero, which raises a ZeroDivisionError. We catch this specific exception using an except block and provide a custom error message.
  2. We also use a more general except block that catches all exceptions (except those already caught) and prints an error message along with the exception.
  3. The else block contains code that executes if no exceptions are raised. In this case, it prints a success message.
  4. The finally block contains code that always executes, regardless of whether an exception was raised. It's often used for cleanup tasks.
Handling exceptions is a critical aspect of writing robust and reliable Python code. It allows your program to gracefully recover from errors, provide helpful error messages, and continue running when problems occur.
Programming Code:
Following code write in: BP_P56.py
# Python Program

# Exception: ZeroDivisionError

num1 = int(input("Enter first Integer Number: "))
num2 = int(input("Enter second Integer Number: "))

# Overcome it by using try-except block
try:
    div = num1 / num2
    print(f" {num1} / {num2} Division is: ", div)
except Exception:
    print("Can't divide by zero.")

# Thanks for Reading.
Output:

Post a Comment

0 Comments

Ad Code

Responsive Advertisement