Grammar/Environments

Python Exception Handling[try, except, else, finally]

This article shows basics of exception handling in Python.

By performing appropriate exception handling, a program can be continued even if an error occurs.

Contents

◆Basics of Exception Handling

  • How to use "try except"
  • How to catch all exceptions
  • How to pass an exception object to a variable

◆Processing when there is no error[try else]

◆Processing always executed[try finally]

sponsored link

Basics of Exception Handling

In the beginning, I show basics of exception handling in Python.

"Exceptions" in Python are various problems (errors) that prevent processing.

If an error occurs, a program is aborted.

However, by performing appropriate exception handling, the program can be continued even if an error occurs.

Exceptions are raised when the code resulted in an error.

In the following example code, "ZeroDivisionError" occurs, indicating that division by zero is not possible.

num = 0

result = 100 / num
print(result)

# ZeroDivisionError : division by zero

By assuming errors and preparing exception handling, troubles can be prevented in advance.

How to use "try except"

I show how to use "try except".

"Exceptions" can be handled using the "try statement".

How to write

try :

code that may cause exception

except Specific Exception :

If there is Exception, then execute this block.

If the try block raises an error, the except block is be executed.

This is the example code.

In the "except block", processing is written when ZeroDivisionError occurs.

num = 2

try :
    result = 100 / num
    print(result)
except ZeroDivisionError :
    print('Enter a non-zero number.')

# 50.0

If ZeroDivisionError occurs, the process in the "except block" is executed.

num = 0

try :
    result = 100 / num
    print(result)
except ZeroDivisionError :
    print('Enter a non-zero number.')

# Enter a non-zero number.

How to catch all exceptions

By specifying " Exception " as a exception type, all exceptions can be caught.

How to write

try :

code that may cause exception

except Exception :

If there is Exception, then execute this block.

This is the example code.

num = 0

try :
    result = 100 / num
    print(result)
except Exception:
    print('An error occurred')
# An error occurred

"Exception" is useful, but any error will not interrupt a process.

Therefore, when an unexpected exception occurs, it becomes difficult to detect an error.

Whenever possible, specify expected exceptions as " exception type".

How to pass an exception object to a variable

We can pass exception object to a variable.

How to write

try :

code that may cause exception

except Exception as Variable :

If there is Exception, then execute this block.

This is the example code.

When "ZeroDivisionError" occurs, the exception object is passed to a variable and printed.

num = 0

try :
    result = 100 / num
    print(result)
except ZeroDivisionError as e:
    print('Enter a non-zero number.')
    print(type(e))
    print(e)
# Enter a non-zero number.
# <class 'ZeroDivisionError'>
# division by zero

I show another example code.

Receives a number via keyboard input and uses it for division.

while True:
    try:
        num = input('Enter a non-zero number. : ')
        result = 100 / int(num)
        print(result)
    except Exception as e:
        print(e)
        print('An error occurred, please re-enter a non-zero number : ')
        continue

# Enter a non-zero number. : 1
# 100.0
# Enter a non-zero number. : 0
# division by zero
# An error occurred, please re-enter a non-zero number :
# Enter a non-zero number. : 10
# 10.0

sponsored link

Processing when there is no error[try else]

In "else block", we can write processing when there is no error.

How to write

try :

code that may cause exception

except Specific Exception :

If there is Exception, then execute this block.

else :

If there is no exception then execute this block.

This is the example code.

num = 1

try :
    result = 100 / num
except Exception as e:
    print(e)
else :
    print('Completed successfully.')
    print(result)

# Completed successfully.
# 100.0

If an error occurs, processing in "else block" is not executed.

num = 0

try :
    result = 100 / num
except Exception as e:
    print(e)
else :
    print('Completed successfully.')
    print(result)

# division by zero

Processing always executed[try finally]

In "finally block", we can write processing always executed.

How to write

try :

code that may cause exception

except Specific Exception :

If there is Exception, then execute this block.

else :

If there is no exception then execute this block.

finally :

This block is always executed.

This is the example code.

num = 1

try :
    result = 100 / num
except Exception as e:
    print(e)
else :
    print('Completed successfully.')
    print(result)
finally :
    print('Calculation finished')

# Completed successfully.
# 100.0
# Calculation finished

sponsored link

-Grammar/Environments
-