Python try-except

Python try-except
The block of code that lets you to test block of code for error that if any error is present in the code or not.

The block of code that allows or lets you to handle the errors identified by the try block , is the except block.

The block of code that lets you to execute the code is the finally block. The finally block execute the code regardless of the result of the try and except block.

Exception Handling
In Python progrmming whenever any error or exception occurs then at that time python stops the execution of the code and generate an error message.

The exceptions generated, can be handled by using the try statement.
For better understanding consider the following example: In the following example the try block will generate an error or exception, because of the reason that 'x' is not defined:

try:

     print(x)

except:

     print("An exception occurred")


Since now the try block has raised an error, so now the except block will be executed.

If try block is not present in the code then at that time the program will crash and raise an error.
The following statement will raise an error, because of the reason that x is not defined:

print(x)


Many Exceptions
You can define any number of exceptions as many you want. For e.g. if you want to execute a special block of code for a special kind of error:
For e.g. if you want to print a message that "Variable x is not defined" if the try block raises a "NameError" and another message that "Something else went wrong" for other errors, then you can write the following code:

try:

     print(x)

except NameError:

     print("Variable x is not defined")

except:

     print("Something else went wrong")


Else
The "else" keyword can be used to define the block of code that is to be executed when no errors are raised:
In the following example, the try block does not raise any error:

try:

     print("Hello")

except:

     print("Something went wrong")

else:

     print("Nothing went wrong")


Finally
If the "finally" block is specified then it will be executed whether the try block generated any error or not.

try:

     print(x)

except:

     print("Something went wrong")

finally:

     print("The 'try except' is finished")


This can be useful to close the objects and clean up the resources:
Try to open a file and write to that file that is not writable:

try:

     f = open("demofile.txt")

     f.write("Lorum Ipsum")

except:

     print("Something went wrong when writing to the file")

finally:

     f.close()