Python raise exception : Learn how exception raise in python and use of try and except in python programming language. It is used in your program to raise an exception as it breaks the current code execution and returns the exception back until it is handled. To throw or raise an exception we use the raise keyword.
Output:-
Trackback (most recent call last):
File “demo_ref_raise.py”, line 4, in <module>
Raise Exception (“sorry, no numbers below zero”)
Exception: sorry, no numbers below zero
Use the else keyword to define the block of codes to be executed if no errors are raised:
Example:-
Try block is do not generate the error,
try:
print(“Hello”)
except:
print(“something went wrong”)
else:
print(“Nothing went wrong”)
Output:-
Hello
Nothing went wrong
def enterange (age):
if age<0:
raisevalueError (“Only positive integers are allowed”)
if age %2==0:
print(“age is even”)
else:
print(“age is odd”)
try:
num=int (input (“Enter your age :”))
enterage (num)
except ValueError:
print(“Only positive integers are allowed”)
except:
print(“something is wrong”)
Output:
Enter your age: 12
Age is even again run and enters the negative number
Enter your age:-12
Only integers are allowed
Finally:-
Used to execute if the try block raises an error or not.
Example:-
try:
print(x)
except:
print(“something went wrong”)
finally:
print(“The ‘try except is finished”)
Output:-
Something went wrong
The ‘try except’ is finished
The exception is handled using the try statement in python language.
But when the exception arises inside try clause the code will handle the exception is written in the except clause.
The try block raises the error and the except block will be executed.
If try block is not used the program will raise an error and get crash.
Example:-
It will raise an error because the x is not defined.
print(x)
Output:-
Trackback (most recent call last):
File “demo_try_except_error.py”, line 3, in<module>
Print(x)
NameError: name’x’ is not defined
Many exceptions:-
The example below will have many exceptions and is described using the example below.
Example:-
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Output:-
Variable x is not defined