This article is participating in Python Theme Month. See the link to the event for more details

Read this tutorial to learn about Python exception handling. It should help you understand how to use try, except, and finally statements in your programs. Read the examples given carefully to get started quickly.

Exception handling is important to creating robust and stable applications. It encourages programmers to write clean, readable, and error-free code.

You’ll agree that even the best code can behave unexpectedly at run time. This could be due to a lack of configuration, or a change in the execution environment, or the user entering the wrong input.

Some of these errors may cause the program to terminate abruptly. With the help of Python exception handling, we can manage these problems and avoid intermittent failures in our code.

First, we must understand the difference between an error and an exception. So, we’ll teach you the basics of Python exception handling.

Python exception handling: Errors and exceptions

What is a mistake?

Errors are errors that occur in a program, such as syntax errors.

It happens at compile time. Let’s look at an example.

if a<5
File "<interactive input>", line 1
    if a < 5
           ^
SyntaxError: invalid syntax
Copy the code

What is an exception?

Errors also occur at run time, and we call them exceptions. An exception is an event that occurs during program execution and interrupts the normal flow of program instructions.

Typically, a Python script throws an exception when it encounters an error condition that it cannot handle.

When a Python script throws an exception, it creates an exception object.

Typically, the script handles the exception immediately. If it does not, the program terminates and prints the trace to the error and its whereabouts.

>>> 1 / 0
Traceback (most recent call last):
 File "<string>", line 301.in run code
 File "<interactive input>", line 1.in <module>
ZeroDivisionError: division by zero
Copy the code

How to handle exceptions using try-except?

What is a try-except statement?

We use the try-except statement to enable exception handling in Python programs.

In the try block, you write code that can throw an exception.

The code that handles or catches exceptions, we put in the except clause.

Python exception handling syntax

Here is the syntax for Python try-except-else blocks.

try: You do your operations here; .exceptExceptionI: Executes this block if there is ExceptionIexceptExceptionII: if there are ExceptionII, perform this piece...else: Executes this block if there is no exception.Copy the code

Take a look – 30 Python tutorials and tips

This is a list of valid use of Python try statements.

  • Depending on requirements, a single try statement can have more than one except statement. In this case, the try block contains statements that can throw different types of exceptions.
  • We can also add a generic except clause that handles all possible exception types.
  • We can even include an else clause after the except clause. If the code in the try block does not throw an exception, the instructions in the else block are executed.

Example of Python exception handling

Let’s walk through a sample code to see how Python try-except works.

try:
   fob = open("test"."w")
   fob.write("Here's my exception handling test file.")
except IOError:
   print 
   "Error: File not found or data read"
else:
   print 
   "Write to file successfully"
   fob.close()
Copy the code

The above code produces the following output.

>> Write the file successfullyCopy the code

Let’s take another example where we try to open a file in READ mode.

We will WRITE it. An exception is thrown when executed.

try:
   fob = open("test"."r")
   fob.write("Here's my test file to verify exception handling in Python.")
except IOError:
   print 
   "Error: File not found or data read"
else:
   print 
   "Write to file successfully"
Copy the code

The above code produces the following output.

>> Error: File not found or data readCopy the code

Except handles all types of exceptions

If we use an empty “except” clause, it will catch all types of exceptions.

However, this is neither a good programming practice nor recommended by anyone.

This is because such a Python try-except block can handle all types of exceptions. But it doesn’t help the programmer find the exception that’s causing the problem.

You can see how to catch all exceptions with the following code.

example

try: You do your operations here; .except: If there are any exceptions, this block...................... is executedelse: Executes this block if there is no exceptionCopy the code

Handle multiple exceptions with except

We can define more than one exception using the same except clause. This means that if the Python interpreter finds a matching exception, it will execute the code written under the except clause.

In short, when we define the except clause this way, we expect the same piece of code to throw different exceptions. In addition, we expect the same action to be taken in every case.

Please refer to the example below.

example

try: You do your operations here; .except(Exception1 [, Exception2 ExceptionN [,...]]]) : if a given list any anomaly, and then perform this piece...else: Executes this block if there is no exceptionCopy the code

How to use try-finally to handle exceptions?

What is a try-finally statement?

We can also enable Python exception handling with the try-finally statement.

Using the try block, we can optionally define a “finally” block. This clause allows us to define the statement we want to execute, regardless of whether the try block throws an exception.

This feature usually occurs when an external resource is released.

This is the code snippet of help.

try: You do your operations here; . This may be skipped due to any exceptionsfinally: This will always be done......................Copy the code

example

One key point is that we can define an “except” or “finally” clause for each try block. You can’t put these together. In addition, you should not use the “else” clause with the “finally” clause.

Let’s take an example to make it clearer.

try:
    fob = open('test'.'w')
    fob.write("Here's my test file to verify try-finally in exception handling.")
    print 'Try block execution'
finally:
    fob.close()
    print 'Finally block execution'
Copy the code

If no exception has occurred, you will see the following output.

>>tryPerform > >finallyperformCopy the code

Suppose we open a file in READ mode and then try to write to it. In this case, the following code will help you handle exceptions.

try:
    fob = open('test'.'r')
    try:
        fob.write("Here's my test file to verify try-finally in exception handling.")
        print 'Try block execution'
    finally:
        fob.close()
        print 'Finally block execution to close the file'
except IOError:
    print "Error: File not found or data read"
Copy the code

In this case, the interpreter throws an exception and displays the following output.

>>finallyBlock execution to close file >> Error: file not found or data readCopy the code

When some code raises an exception in the try block, execution is immediately passed to the “finally” block. After all statements in the finally block are executed, the exception is restored to the except block. But there must be a higher level next to a “try except” statement.

Throw an exception with a parameter

What is ascension?

We can use the raise keyword to force an exception to be raised.

We can also choose to pass the value to the exception and specify why it happened.

Improve the grammar

This is the syntax for calling the “raise” method.

raise [Exception [, args [, traceback]]]
Copy the code

Where is it,

  • Under “Exception” – specify its name.
  • “Args” is optional and represents the value of the exception parameter.
  • The last parameter, “traceback”, is also optional and, if present, is the traceback object for the exception.

Let’s take an example to prove the point.

Filling the sample

>>> raise MemoryError
Traceback (most recent call last):
...
MemoryError
 
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument
 
 
>>> try:
      a = int(input("Enter a positive integer value: "))
     if a <= 0:
            raise ValueError("This is not a positive number!!")
    except ValueError as ve:
      print(ve)
 
 
Following Output is displayed ifWe enter a negative number: Enter a positive integer: -5
 
This is not a positive number!!
Copy the code

Create custom exceptions in Python

What is a custom exception?

Custom exceptions are those created by the programmer.

He does this by adding a new class. The trick here is to derive a custom exception class from a basic exception class.

Most built-in exceptions also have classes.

Create an exception class in Python

>>> class UserDefinedError(Exception) :
.    pass
 
>>> raise UserDefinedError
Traceback (most recent call last):
...
__main__.UserDefinedError
 
>>> raise UserDefinedError("An error occurred")
Traceback (most recent call last):
...
__main__.UserDefinedError: An error occurred
Copy the code

In the code snippet above, you can see that we created a user-defined exception class, “UserDefinedError.” It uses the base Exception class as its parent. Therefore, the new user-defined exception class will raise an exception just like any other exception class, that is, by calling the “raise” statement with an optional error message.

Let’s take an example.

example

In this example, we will show how to throw a user-defined exception and catch an error in a program.

The program prompts the user to enter the alphabet again and again until he enters only the stored alphabet.

To ask for help, the program provides the user with hints so he can find the correct alphabet. In addition, he can check whether his guess is higher or lower than the stored alphabet.

# Define Python user-defined exceptions
class Error(Exception) :
   """Base class for other exceptions"""
   pass
 
class InputTooSmallError(Error) :
   """Raised when the entered alpahbet is smaller than the actual one"""
   pass
 
class InputTooLargeError(Error) :
   """Raised when the entered alpahbet is larger than the actual one"""
   pass

# Our main program
# User guesses a letter until he/she gets it right
 
# You need to guess the letter
alphabet = 'm'
 
while True:
   try:
       apb =  input("Enter a letter:")
       if apb < alphabet:
           raise InputTooSmallError
       elif apb > alphabet:
           raise InputTooLargeError
       break
   except InputTooSmallError:
       print("The letter is too small. Try again!")
       print(' ')
   except InputTooLargeError:
       print("The letter is too big. Try again!")
       print(' ')
 
print("Congratulations! You guessed it.")
Copy the code

Let’s test the program by providing different inputs.

Type a letter: c is too small, try again! Type a letter: s is too big, try again! Enter a letter: q input letter is too big, try again! Enter a letter: k is too small, try again! Enter a letter: M Congratulations! You guessed itCopy the code

So you can see that we’ve defined a base class called Error in this program. It raises two exceptions (” InputTooSmallError “and” InputTooLargeError “) derived from the base class. This is the standard way to define user-defined exceptions in Python programming.

Python built-in Exceptions

Exception The reason for the error
AirthmeticError For errors in numerical calculations
AssertionError When the assert statement fails
AttributeError When attribute assignment or reference fails
EOFError If there is no input or file pointer in EOF
Exception It is the base class for all exceptions.
EnvironmentError For errors that occur outside of the Python environment.
FloatingPointError Occurs when a floating-point operation fails.
GeneratorExit If the generator’s <close()> method is called.
ImportError Occurs when the imported module is unavailable.
IOError If the input/output operation fails.
IndexError When the index of a sequence is out of range.
KeyError If the specified key is not available in the dictionary.
KeyboardInterrupt When the user presses the break key (Ctrl+ C or Delete).
MemoryError If the memory for the operation is insufficient.
NameError When the variable is not available locally or globally.
NotImplementedError If the abstract method is not available.
OSError When the system operation fails.
OverflowError Occurs when the result of an arithmetic operation is out of range.
ReferenceError When a weak reference proxy accesses a garbage collection reference.
RuntimeError If the generated error does not belong to any category.
StandardError It is the base class for all built-in exceptions except and.
StopIteration The <next()> function has no other items to return.
SyntaxError For errors in Python syntax.
IndentationError Happens if the indent is not correct.
TabError Used for inconsistent tabs and Spaces.
SystemError When the interpreter detects an internal error.
SystemExit Raised by the <sys.exit()> function.
TypeError When a function uses an object of the wrong type.
UnboundLocalError If code is executed using an unassigned reference.
UnicodeError Used for Unicode encoding or decoding errors.
ValueError When a function receives an invalid value.
ZeroDivisionError If the second operand of a division or modular operation is zero.

Summary – Python exception handling concepts

Most of the time, my goal is to find a topic that will help the reader in his or her work. That’s why we introduced this article to Exception handling in Python. If you enjoyed this article and are interested in seeing more of it, follow me here (Github/Gitee) for more information. Here is a summary of all my original and work source code

More on this at 🧵

  • Python Multithreading tutorial | Python theme month
  • Python Socket programming essentials | Python theme month
  • 30 Python tutorials and tips | Python theme month
  • Python statements, expressions, and indentation | Python theme month
  • Python keywords, identifiers, and variables | Python theme month
  • How to write comments and multi-line comments in Python | Python Theme Month
  • Python data types — Basic to advanced learning | Python topic month

Recommended articles of the past:

  • 20 Python Tips Everyone must Know | Python Theme month
  • 100 Basic Python Interview Questions Part 1 (1-20) | Python topic month
  • 100 Basic Python Interview Questions Part 2 (21-40) | Python topic month
  • 100 Basic Python Interview Questions Part 3 (41-60) | Python topic month
  • 100 Basic Python Interview Questions Part 4 (61-80) | Python topic month
  • 100 Basic Python Interview Questions Part 5 (81-100) | Python topic month

If you do learn something new from this post, like it, bookmark it and share it with your friends. 🤗 Finally, don’t forget ❤ or 📑 for support