try and excep

try() is used in Error and Exception Handling There are two kinds of errors :

  • Syntax Error : Also known as Parsing Errors, most basic. Arise when the Python parser is unable to understand a line of code.

  • Exception : Errors which are detected during execution. eg – ZeroDivisionError.

List of Exception Errors :

  • IOError : if file can’t be opened

  • KeyboardInterrupt : when an unrequired key is pressed by the user

  • ValueError : when built-in function receives a wrong argument

  • EOFError : if End-Of-File is hit without reading any data

  • ImportError : if it is unable to find the module

Now, here comes the task to handle these errors within our code in Python. So here we need try-except statements.

Basic Syntax : 
 try:
    // Code
 except:
    // Code

How try() works?

  • First try clause is executed i.e. the code between try and except clause.

  • If there is no exception, then only try clause will run, except clause is finished.

  • If any exception occured, try clause will be skipped and except clause will run.

  • If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception left unhandled, then the execution stops.

  • A try statement can have more than one except clause

Code 1 : No exception, so try clause will run.filter_none

# Python code to illustrate 
# working of try()  
def divide(x, y): 
    try: 
        # Floor Division : Gives only Fractional Part as Answer 
        result = x // y 
        print("Yeah ! Your answer is :", result) 
    except ZeroDivisionError: 
        print("Sorry ! You are dividing by zero ") 
  
# Look at parameters and note the working of Program 
divide(3, 2) 

Output :

('Yeah ! Your answer is :', 1)

Code 1 : There is an exception so only except clause will run.filter_none

# Python code to illustrate 
# working of try()  
def divide(x, y): 
    try: 
        # Floor Division : Gives only Fractional Part as Answer 
        result = x // y 
        print("Yeah ! Your answer is :", result) 
    except ZeroDivisionError: 
        print("Sorry ! You are dividing by zero ") 
  
# Look at parameters and note the working of Program 
divide(3, 0) 

Output :

Sorry ! You are dividing by zero

Related Articles:

This article is contributed by Mohit Gupta_OMG 😀. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Python Try Except

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you 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:

Example

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

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

try:
  print(x)
except:
  print("An exception occurred")
An exception occurred

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:

Example

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

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

print(x)
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

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

Example

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

#The try block will generate a NameError, because x is not defined:

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")
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:

Example

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

#The try block does not raise any errors, so the else block is executed:

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")
Hello
Nothing went wrong

Finally

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

Example

#The finally block gets executed no matter if the try block raises any errors or not:

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")
Something went wrong
The 'try except' is finished

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

Example

Try to open and write to a file that is not writable:

#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
Something went wrong when writing to the file

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

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.

Example

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

x = -1

if x < 0:
  raise Exception("Sorry, no numbers below zero")
Traceback (most recent call last):
  File "demo_ref_keyword_raise.py", line 4, in <module>
    raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero

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.

Example

Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:
  raise TypeError("Only integers are allowed")
Traceback (most recent call last):
  File "demo_ref_keyword_raise2.py", line 4, in <module>
    raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed

Reference : https://www.w3schools.com/python/python_try_except.asp

Last updated