TRY...EXCEPT



Python - TRY...EXCEPT


The 'try' block lets us to test a block of code for errors.

The 'except' block lets us to handle the error.

The 'finally' block lets us to execute code, regardless of the result of the try- and except blocks.


Exception Handling :


When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

These exceptions can be handled using the try statement.


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

try:
    print(x)
except:
        print("an exception occured")


=======o/p=======

an exception occured


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

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


This statement will raise an error, because x is not defined:

#This will raise an exception, because x is not defined:

print(x)

=======o/p======

Traceback (most recent call last):
  File "demo_try_except_error.py", line 3, in <module>
    print(x)
NameError: name 'x' is not defined

Many Exceptions :


We can define as many exception blocks as we want, e.g. if you want to execute a special block of code for a special kind of error.


Print one message if the try block raises a NameError and another for other errors:

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

======o/p======

variable x is not defined

Else :


You can use the else keyword to define a block of code to be executed if no errors were raised.


In this example, the try block does not generate any error:

try:
    print("hello freedom tutorials")
except:
        print("something went wrong")
else:
            print("nothing went wrong")



======o/p======

hello freedom tutorials
nothing went wrong




Finally :


The finally block, if specified, will be executed regardless if the try block raises an error or not.


try:
    print(x)
except:
    print("something went wrong")
finally:
    print("execution finished")

======o/p=====

something went wrong
execution finished
try:
    print("hello")
except:
    print("something went wrong")
finally:
    print("execution finished")

=======O/P=======

hello
execution finished

This can be useful to close objects and clean up resources.


#The try block will raise an error when trying to write to a read-only file:

try:
  f = open("demofile.txt")
  f.write("Lorum Ipsum")
except:
  print("Something went wrong when writing to the file")
finally:
  f.close()

#The program can continue, without leaving the file object open


=======O/P=======

Something went wrong when writing to the file


Raise an exception :


As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.


Raise an error and stop the program if x is lower than 0:

x=52
if x<54:
 raise exception("sorry there is no number greater than 54") 

======o/p=====

    raise exception("sorry there is no number greater than 54")
NameError: name 'exception' is not defined

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.


Raise a TypeError if x is not an integer:

x="hello"
if not type(x) is int:
    raise TypeError("only integers are allowed")

=======o/p======

 raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed
x=586
if not type(x) is str:
    raise TypeError("only strings are allowed")

=======o/p======= 

raise TypeError("Only strings are allowed")
TypeError: Only strings are allowed


RegEx SETS

Python - RegEx SETS

posted on 2019-11-12 23:06:24 - Python Tutorials


RegEx_Functions

Python - RegEx_Functions

posted on 2019-11-09 06:07:29 - Python Tutorials


RegEx_Sets

Python - RegEx_Sets

posted on 2019-11-09 05:30:54 - Python Tutorials


Prompt Examples

ChatGPT Prompt Examples

posted on 2023-06-21 22:37:19 - ChatGPT Tutorials


Use Cases

Chat GPT Key Use Cases

posted on 2023-06-21 21:03:17 - ChatGPT Tutorials


Prompt Frameworks

Prompt Frameworks

posted on 2023-06-21 19:33:06 - ChatGPT Tutorials