WHAT IS PYTHON TRY EXCEPT?

TRY and EXCEPT block is used in the code for the exception handling.

Exception Handling

Whenever an error or exception occur in our code while executing, the Python will normally stop and generate an error message.

These exceptions can be handled using the try statement.

The try block is used for testing a block of code for errors.

The except block is used to handle the error.

The else block is used to execute code when there is no error.

The finally block is used to execute code, regardless of the result of the try- and except blocks.

Example-

When the try block raises an error, the except block will be executed.

Without the try block, in case of error, the program will crash and raise an error:

#The try block will generate an error, because x is not #defined:

try:
  print(x)
except: #execute when there is error in try block
  print("An exception occurred")
else:   #execute when there is no error
  print("Nothing went wrong") 
finally: #execute when the try except block is executed
  print("The 'try except' and 'finally' is executed")

Output

An exception occurred
The 'try except' and 'finally' is executed

Raise an exception
We have an option to throw an exception if a condition occurs.

To throw (or raise) an exception we can use raise keyword.

x = -1

if x < 0:
  raise Exception("negative value is not allowed")

Posted

in

Tags:

Comments

Leave a Reply