All TalkersCode Topics

Follow TalkersCode On Social Media

Python Raise Exception With Message

Last Updated : Aug 2, 2023

Python Raise Exception With Message

In this article we will show you the solution of python raise exception with message, Python programmers can benefit greatly from exceptions. They give you the ability to manage errors, produce more understandable code, and model implementation effects.

You will be able to use Python exceptions to code more effectively by the end of this session.

Exceptions are frequently referred to as logical errors. They take place when a programme is running.

When a mistake is found, Python creates an exception you can address rather than leaving the programme to crash.

It is analogous to the temperature alert that appears on your iPhone when it becomes too hot.

The phone doesn't let itself overheat; instead, it stops working and asks you to fix the problem by cooling it down.

Similar to this, Python exceptions prevent the programme from continuing and give you a chance to fix the problem.

We will now discuss the idea of how to raise exceptions with a message with an example.

Step By Step Guide On Python Raise Exception With Message :-

Code 1

# Python program to raise an exception
# check_age function checks the age
def check_age(age):
    if age < 18:
        raise Exception(" TalkersCode Age must be 18 or above. ")
        print(" Age is valid ")
except Exception as e:
    print(" An error occurred: ", e)

Code 2

    f = open("tc.txt", 'r')
except FileNotFoundError as fne:
    print('Creating file...')
    f = open("tc.txt", 'w')
    print('Closing file')
  1. Create the "check_age" function and the "age" parameter.
  2. The "if" clause determines if the "age" is under 18.
  3. The function raises an exception with the message "TalkersCode" if the "age" is less than 18 Must be at least 18 years old.
  4. The function prints the phrase "Age is valid" if the value of "age" is more than or equal to 18.
  5. We employ a "try-except" block outside the "check_age" function.
  6. With the argument 17, which is below the age of 18, we call the "check_age" function.
  7. The function produces an exception because the "age" is less than 18 years old.
  8. The "except" block handles the exception and prints the error message from the "raise" command along with the message "An error occurred:".

Conclusion :-

As a result, we have successfully learned how to raise exceptions with messages with an example.

To raise an exception in Python, use the raise statement. You can raise the same exception or a different exception while managing exceptions.

I hope this article on python raise exception with message helps you and the steps and method mentioned above are easy to follow and implement.

Latest Tutorials