[go: up one dir, main page]

0% found this document useful (0 votes)
53 views6 pages

Raise As Exception

The raise statement in Python is used to raise exceptions. Try-except blocks can be used to manage exceptions, which are errors that occur during program execution. When an exception is triggered, program execution moves to the closest exception handler. Raise can be used inside functions to indicate an error condition. Custom exceptions can also be created by defining exception classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views6 pages

Raise As Exception

The raise statement in Python is used to raise exceptions. Try-except blocks can be used to manage exceptions, which are errors that occur during program execution. When an exception is triggered, program execution moves to the closest exception handler. Raise can be used inside functions to indicate an error condition. Custom exceptions can also be created by defining exception classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Python Raise an Exception

The raise statement in Python is used to raise an exception. Try-except blocks can be used
to manage exceptions, which are errors that happen while a programme is running. When
an exception is triggered, the programme goes to the closest exception handler, interrupting
the regular flow of execution.

o The raise keyword is typically used inside a function or method, and is used to
indicate an error condition.
o We can throw an exception and immediately halt the running of your programme
by using the raise keyword.
o Python looks for the closest exception handler, which is often defined using a try-
except block, when an exception is triggered.
o If an exception handler is discovered, its code is performed, and the try-except
block's starting point is reached again.
o If an exception handler cannot be located, the software crashes and an error message
appears.

Example:

# Python program to raise an exception

# divide function

def divide(a, b):

if b == 0:

raise Exception(" Cannot divide by zero. ")

return a / b

try:

result = divide(10, 0)

except Exception as e:

print(" An error occurred: ", e)


output:

An error occurred: Cannot divide by zero.

In this illustration, the division function accepts the inputs a and b, and if b equals zero,
an exception is raised. The try block catches this exception, and the unless block prints
the error message.

Example-2

# Python program to raise an exception


# check_age function checks the age
def check_age(age):
if age < 18:
raise Exception(" Age must be 18 or above. ")
else:
print(" Age is valid. ")

try:
check_age(17)
except Exception as e:
print(" An error occurred: ", e)

Output:

An error occurred: Age must be 18 or above.

The check age method in this illustration accepts the input age and throws an exception if
age is less than 18. The try block catches this exception, and the unless block prints the
error message. This demonstrates how you can raise and handle exceptions in Python.
You can raise any type of exception, such as ValueError, TypeError, KeyError, etc. to
indicate specific errors in your code.

# Python program for Handling raising exceptions


try:
# code that might raise an exception
value = int("a")
except ValueError:
# code that handles the ValueError exception
print(" Invalid value ")
except TypeError:
# code that handles the TypeError exception
print(" Invalid type ")

output:

Invalid Value
We attempt to change the string "a" to an integer in this instance, which results in a
ValueError. The first unless block recognises the exception and produces a message
stating that the value is incorrect. A different kind of exception would be handled by the
next except block if it were to arise.

The finally block can also be employed to run code that has to be run whether or not this
exception was triggered. For instance:

Code
try:
# code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
# code that handles the exception
print(" Cannot divide by zero. ")
finally:
# code that must be executed regardless of whether an exception was raised or not
print(" The finally block is always executed. ")
Output:

Cannot divide by zero.


The finally block is always executed.

Python User-Defined Exception


# define Python user-defined exceptions
class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass

# you need to guess this number


number = 18

try:
input_num = int(input("Enter a number: "))
if input_num < number:
raise InvalidAgeException
else:
print("Eligible to Vote")

except InvalidAgeException:
print("Exception occurred: Invalid Age")

Customizing Exception Classes


Exception class is just like any normal class. Thus, we can customize this class as per our
requirements, like giving multiple arguments to its constructor.

For example, consider a voting system. It takes various details of the person as well as
checks if all the values entered are appropriate. Here, we are trying to create a class that
performs this task as well as throws an exception in case the age of the person is less than
18.
class VotingPerson(Exception):
# Raised when the input age is less than 18
def __inti__(self, name, id, age):
self.name = name
self.id = id
self.age = age

# try taking details of the users,


# if the age is inappropriate, throw an exception

try:
name = input("Enter name")
id = int(input("Enter id"))
age = int(input("Enter age"))
if age<18 :
raise VotingPerson
vote1 = VotingPerson(name,id,age)
print("Thanks for Voting")
except Exception as e:
print("Sorry you are not eligible for voting",e)

You might also like