Python try except any error

Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand exceptions are raised when some internal events occur which changes the normal flow of the program.Note For

Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.
Note: For more information, refer to Errors and Exceptions in Python
Some of the common Exception Errors are : 
 

  • IOError: if the 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

Try Except in Python

Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block.
 

Syntax: 

try:
    # Some Code
except:
    # Executed if error in the
    # try block

How try() works? 
 

  • First, the try clause is executed i.e. the code between try and except clause.
  • If there is no exception, then only the try clause will run, except the clause is finished.
  • If any exception occurs, the 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 is left unhandled, then the execution stops.
  • A try statement can have more than one except clause

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

Python3

def divide(x, y):

    try:

        result = x // y

        print("Yeah ! Your answer is :", result)

    except ZeroDivisionError:

        print("Sorry ! You are dividing by zero ")

divide(3, 2)

Auxiliary Space: O(1)

Output : 
 

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

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

Python3

def divide(x, y):

    try:

        result = x // y

        print("Yeah ! Your answer is :", result)

    except ZeroDivisionError:

        print("Sorry ! You are dividing by zero ")

divide(3, 0)

Output : 
 

Sorry ! You are dividing by zero

Else Clause

In python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.
 

Syntax:

try:
    # Some Code
except:
    # Executed if error in the
    # try block
else:
    # execute if no exception

Code:

Python3

def AbyB(a , b):

    try:

        c = ((a+b) // (a-b))

    except ZeroDivisionError:

        print ("a/b result in 0")

    else:

        print (c)

AbyB(2.0, 3.0)

AbyB(3.0, 3.0)

Output:

-5.0
a/b result in 0

Finally Keyword in Python

Python provides a keyword finally, which is always executed after the try and except blocks. The final block always executes after normal termination of try block or after try block terminates due to some exceptions.
 

Syntax:

try:
    # Some Code
except:
    # Executed if error in the
    # try block
else:
    # execute if no exception
finally:
    # Some code .....(always executed)

Code:

Python3

try:

    k = 5//0

    print(k)

except ZeroDivisionError:   

    print("Can't divide by zero")

finally:

    print('This is always executed'

Output:

Can't divide by zero
This is always executed

Related Articles: 
 

  • Output Questions
  • Exception Handling in Python
  • User-Defined Exceptions

This article is contributed by Mohit Gupta_OMG 😀. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
 

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Raising and Handling Python Exceptions

A Python program terminates as soon as it encounters an error. In Python, an error can be a syntax error or an exception. In this article, you will see what an exception is and how it differs from a syntax error. After that, you will learn about raising exceptions and making assertions. Then, you’ll finish with a demonstration of the try and except block.

An introduction to exceptions in Python

Exceptions versus Syntax Errors

Syntax errors occur when the parser detects an incorrect statement. Observe the following example:

>>> print( 0 / 0 ))
  File "<stdin>", line 1
    print( 0 / 0 ))
                  ^
SyntaxError: invalid syntax

The arrow indicates where the parser ran into the syntax error. In this example, there was one bracket too many. Remove it and run your code again:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

This time, you ran into an exception error. This type of error occurs whenever syntactically correct Python code results in an error. The last line of the message indicated what type of exception error you ran into.

Instead of showing the message exception error, Python details what type of exception error was encountered. In this case, it was a ZeroDivisionError. Python comes with various built-in exceptions as well as the possibility to create self-defined exceptions.

Raising an Exception

We can use raise to throw an exception if a condition occurs. The statement can be complemented with a custom exception.

Illustration of  raise statement usage

If you want to throw an error when a certain condition occurs using raise, you could go about it like this:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))

When you run this code, the output will be the following:

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10

The program comes to a halt and displays our exception to screen, offering clues about what went wrong.

The AssertionError Exception

Instead of waiting for a program to crash midway, you can also start by making an assertion in Python. We assert that a certain condition is met. If this condition turns out to be True, then that is excellent! The program can continue. If the condition turns out to be False, you can have the program throw an AssertionError exception.

Python assert statement

Have a look at the following example, where it is asserted that the code will be executed on a Linux system:

import sys
assert ('linux' in sys.platform), "This code runs on Linux only."

If you run this code on a Linux machine, the assertion passes. If you were to run this code on a Windows machine, the outcome of the assertion would be False and the result would be the following:

Traceback (most recent call last):
  File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.

In this example, throwing an AssertionError exception is the last thing that the program will do. The program will come to halt and will not continue. What if that is not what you want?

The try and except Block: Handling Exceptions

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.

Diagram showing try and except statements

As you saw earlier, when syntactically correct code runs into an error, Python will throw an exception error. This exception error will crash the program if it is unhandled. The except clause determines how your program responds to exceptions.

The following function can help you understand the try and except block:

def linux_interaction():
    assert ('linux' in sys.platform), "Function can only run on Linux systems."
    print('Doing something.')

The linux_interaction() can only run on a Linux system. The assert in this function will throw an AssertionError exception if you call it on an operating system other then Linux.

You can give the function a try using the following code:

try:
    linux_interaction()
except:
    pass

The way you handled the error here is by handing out a pass. If you were to run this code on a Windows machine, you would get the following output:

You got nothing. The good thing here is that the program did not crash. But it would be nice to see if some type of exception occurred whenever you ran your code. To this end, you can change the pass into something that would generate an informative message, like so:

try:
    linux_interaction()
except:
    print('Linux function was not executed')

Execute this code on a Windows machine:

Linux function was not executed

When an exception occurs in a program running this function, the program will continue as well as inform you about the fact that the function call was not successful.

What you did not get to see was the type of error that was thrown as a result of the function call. In order to see exactly what went wrong, you would need to catch the error that the function threw.

The following code is an example where you capture the AssertionError and output that message to screen:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
    print('The linux_interaction() function was not executed')

Running this function on a Windows machine outputs the following:

Function can only run on Linux systems.
The linux_interaction() function was not executed

The first message is the AssertionError, informing you that the function can only be executed on a Linux machine. The second message tells you which function was not executed.

In the previous example, you called a function that you wrote yourself. When you executed the function, you caught the AssertionError exception and printed it to screen.

Here’s another example where you open a file and use a built-in exception:

try:
    with open('file.log') as file:
        read_data = file.read()
except:
    print('Could not open file.log')

If file.log does not exist, this block of code will output the following:

This is an informative message, and our program will still continue to run. In the Python docs, you can see that there are a lot of built-in exceptions that you can use here. One exception described on that page is the following:

Exception FileNotFoundError

Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.

To catch this type of exception and print it to screen, you could use the following code:

try:
    with open('file.log') as file:
        read_data = file.read()
except FileNotFoundError as fnf_error:
    print(fnf_error)

In this case, if file.log does not exist, the output will be the following:

[Errno 2] No such file or directory: 'file.log'

You can have more than one function call in your try clause and anticipate catching various exceptions. A thing to note here is that the code in the try clause will stop as soon as an exception is encountered.

Look at the following code. Here, you first call the linux_interaction() function and then try to open a file:

try:
    linux_interaction()
    with open('file.log') as file:
        read_data = file.read()
except FileNotFoundError as fnf_error:
    print(fnf_error)
except AssertionError as error:
    print(error)
    print('Linux linux_interaction() function was not executed')

If the file does not exist, running this code on a Windows machine will output the following:

Function can only run on Linux systems.
Linux linux_interaction() function was not executed

Inside the try clause, you ran into an exception immediately and did not get to the part where you attempt to open file.log. Now look at what happens when you run the code on a Linux machine:

[Errno 2] No such file or directory: 'file.log'

Here are the key takeaways:

  • A try clause is executed up until the point where the first exception is encountered.
  • Inside the except clause, or the exception handler, you determine how the program responds to the exception.
  • You can anticipate multiple exceptions and differentiate how the program should respond to them.
  • Avoid using bare except clauses.

The else Clause

In Python, using the else statement, you can instruct a program to execute a certain block of code only in the absence of exceptions.

Diagram of try, except, and else statements in Python

Look at the following example:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    print('Executing the else clause.')

If you were to run this code on a Linux system, the output would be the following:

Doing something.
Executing the else clause.

Because the program did not run into any exceptions, the else clause was executed.

You can also try to run code inside the else clause and catch possible exceptions there as well:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)

If you were to execute this code on a Linux machine, you would get the following result:

Doing something.
[Errno 2] No such file or directory: 'file.log'

From the output, you can see that the linux_interaction() function ran. Because no exceptions were encountered, an attempt to open file.log was made. That file did not exist, and instead of opening the file, you caught the FileNotFoundError exception.

Cleaning Up After Using finally

Imagine that you always had to implement some sort of action to clean up after executing your code. Python enables you to do so using the finally clause.

Diagram explaining try except else finally statements

Have a look at the following example:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)
finally:
    print('Cleaning up, irrespective of any exceptions.')

In the previous code, everything in the finally clause will be executed. It does not matter if you encounter an exception somewhere in the try or else clauses. Running the previous code on a Windows machine would output the following:

Function can only run on Linux systems.
Cleaning up, irrespective of any exceptions.

Summing Up

After seeing the difference between syntax errors and exceptions, you learned about various ways to raise, catch, and handle exceptions in Python. In this article, you saw the following options:

  • raise allows you to throw an exception at any time.
  • assert enables you to verify if a certain condition is met and throw an exception if it isn’t.
  • In the try clause, all statements are executed until an exception is encountered.
  • except is used to catch and handle the exception(s) that are encountered in the try clause.
  • else lets you code sections that should run only when no exceptions are encountered in the try clause.
  • finally enables you to execute sections of code that should always run, with or without any previously encountered exceptions.

Hopefully, this article helped you understand the basic tools that Python has to offer when dealing with exceptions.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Raising and Handling Python Exceptions

The try except statement can handle exceptions. Exceptions may happen when you run a program.

Exceptions are errors that happen during execution of the program. Python won’t tell you about errors like syntax errors (grammar faults), instead it will abruptly stop.

An abrupt exit is bad for both the end user and developer.

Instead of an emergency halt, you can use a try except statement to properly deal with the problem. An emergency halt will happen if you do not properly handle exceptions.

Related course: Complete Python Programming Course & Exercises

What are exceptions in Python?

Python has built-in exceptions which can output an error. If an error occurs while running the program, it’s called an exception.

If an exception occurs, the type of exception is shown. Exceptions needs to be dealt with or the program will crash. To handle exceptions, the try-catch block is used.

Some exceptions you may have seen before are FileNotFoundError, ZeroDivisionError or ImportError but there are many more.

All exceptions in Python inherit from the class BaseException. If you open the Python interactive shell and type the following statement it will list all built-in exceptions:

The idea of the try-except clause is to handle exceptions (errors at runtime). The syntax of the try-except block is:

1
2
3
4
try:
<do something>
except Exception:
<handle the error>

The idea of the try-except block is this:

  • try: the code with the exception(s) to catch. If an exception is raised, it jumps straight into the except block.

  • except: this code is only executed if an exception occured in the try block. The except block is required with a try block, even if it contains only the pass statement.

It may be combined with the else and finally keywords.

  • else: Code in the else block is only executed if no exceptions were raised in the try block.

  • finally: The code in the finally block is always executed, regardless of if a an exception was raised or not.

Catching Exceptions in Python

The try-except block can handle exceptions. This prevents abrupt exits of the program on error. In the example below we purposely raise an exception.

1
2
3
4
5
6
try: 
1 / 0
except ZeroDivisionError:
print('Divided by zero')

print('Should reach here')

After the except block, the program continues. Without a try-except block, the last line wouldn’t be reached as the program would crash.

 $ python3 example.py

Divided by zero
Should reach here

In the above example we catch the specific exception ZeroDivisionError. You can handle any exception like this:

1
2
3
4
5
6
try: 
open("fantasy.txt")
except:
print('Something went wrong')

print('Should reach here')

You can write different logic for each type of exception that happens:

1
2
3
4
5
6
7
8
9
10
try: 

except FileNotFoundError:

except IsADirectoryError:

except:


print('Should reach here')

Related course: Complete Python Programming Course & Exercises

try-except

Lets take do a real world example of the try-except block.

The program asks for numeric user input. Instead the user types characters in the input box. The program normally would crash. But with a try-except block it can be handled properly.

The try except statement prevents the program from crashing and properly deals with it.

1
2
3
4
5
6
try:
x = input("Enter number: ")
x = x + 1
print(x)
except:
print("Invalid input")

Entering invalid input, makes the program continue normally:

try except

The try except statement can be extended with the finally keyword, this will be executed if no exception is thrown:

1
2
finally:
print("Valid input.")

The program continues execution if no exception has been thrown.

There are different kinds of exceptions: ZeroDivisionError, NameError, TypeError and so on. Sometimes modules define their own exceptions.

The try-except block works for function calls too:

1
2
3
4
5
6
7
8
9
def fail():
1 / 0

try:
fail()
except:
print('Exception occured')

print('Program continues')

This outputs:

 $ python3 example.py

Exception occured
Program continues

If you are a beginner, then I highly recommend this book.

try finally

A try-except block can have the finally clause (optionally). The finally clause is always executed.
So the general idea is:

1
2
3
4
5
6
try:
<do something>
except Exception:
<handle the error>
finally:
<cleanup>

For instance: if you open a file you’ll want to close it, you can do so in the finally clause.

1
2
3
4
5
6
7
8
try: 
f = open("test.txt")
except:
print('Could not open file')
finally:
f.close()

print('Program continue')

try else

The else clause is executed if and only if no exception is raised. This is different from the finally clause that’s always executed.

1
2
3
4
5
6
7
8
try:
x = 1
except:
print('Failed to set x')
else:
print('No exception occured')
finally:
print('We always do this')

Output:

 No exception occured
We always do this

You can catch many types of exceptions this way, where the else clause is executed only if no exception happens.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
try:
lunch()
except SyntaxError:
print('Fix your syntax')
except TypeError:
print('Oh no! A TypeError has occured')
except ValueError:
print('A ValueError occured!')
except ZeroDivisionError:
print('Did by zero?')
else:
print('No exception')
finally:
print('Ok then')

Raise Exception

Exceptions are raised when an error occurs. But in Python you can also force an exception to occur with the keyword raise.

Any type of exception can be raised:

1
2
3
4
>>> raise MemoryError("Out of memory")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError: Out of memory
1
2
3
4
5
>>> raise ValueError("Wrong value")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Wrong value
>>>

Related course: Complete Python Programming Course & Exercises

Built-in exceptions

A list of Python’s Built-in Exceptions is shown below. This list shows the Exception and why it is thrown (raised).

Exception Cause of Error
AssertionError if assert statement fails.
AttributeError if attribute assignment or reference fails.
EOFError if the input() functions hits end-of-file condition.
FloatingPointError if a floating point operation fails.
GeneratorExit Raise if a generator’s close() method is called.
ImportError if the imported module is not found.
IndexError if index of a sequence is out of range.
KeyError if a key is not found in a dictionary.
KeyboardInterrupt if the user hits interrupt key (Ctrl+c or delete).
MemoryError if an operation runs out of memory.
NameError if a variable is not found in local or global scope.
NotImplementedError by abstract methods.
OSError if system operation causes system related error.
OverflowError if result of an arithmetic operation is too large to be represented.
ReferenceError if a weak reference proxy is used to access a garbage collected referent.
RuntimeError if an error does not fall under any other category.
StopIteration by next() function to indicate that there is no further item to be returned by iterator.
SyntaxError by parser if syntax error is encountered.
IndentationError if there is incorrect indentation.
TabError if indentation consists of inconsistent tabs and spaces.
SystemError if interpreter detects internal error.
SystemExit by sys.exit() function.
TypeError if a function or operation is applied to an object of incorrect type.
UnboundLocalError if a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeError if a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError if a Unicode-related error occurs during encoding.
UnicodeDecodeError if a Unicode-related error occurs during decoding.
UnicodeTranslateError if a Unicode-related error occurs during translating.
ValueError if a function gets argument of correct type but improper value.
ZeroDivisionError if second operand of division or modulo operation is zero.

User-defined Exceptions

Python has many standard types of exceptions, but they may not always serve your purpose.
Your program can have your own type of exceptions.

To create a user-defined exception, you have to create a class that inherits from Exception.

1
2
3
4
class LunchError(Exception):
pass

raise LunchError("Programmer went to lunch")

You made a user-defined exception named LunchError in the above code. You can raise this new exception if an error occurs.

Outputs your custom error:

 $ python3 example.py
Traceback (most recent call last):
File “example.py”, line 5, in
raise LunchError(“Programmer went to lunch”)
main.LunchError: Programmer went to lunch

Your program can have many user-defined exceptions. The program below throws exceptions based on a new projects money:

1
2
3
4
5
6
7
8
9
10
11
class NoMoneyException(Exception):
pass

class OutOfBudget(Exception):
pass

balance = int(input("Enter a balance: "))
if balance < 1000:
raise NoMoneyException
elif balance > 10000:
raise OutOfBudget

Here are some sample runs:

 $ python3 example.py
Enter a balance: 500
Traceback (most recent call last):
File “example.py”, line 10, in
raise NoMoneyException
main.NoMoneyException
 $ python3 example.py
$ python3 example.py
Enter a balance: 100000
Traceback (most recent call last):
File “example.py”, line 12, in
raise OutOfBudget
main.OutOfBudget

It is a good practice to put all user-defined exceptions in a separate file (exceptions.py or errors.py). This is common practice in standard modules too.

If you are a beginner, then I highly recommend this book.

Exercises

  1. Can try-except be used to catch invalid keyboard input?
  2. Can try-except catch the error if a file can’t be opened?
  3. When would you not use try-except?

Download examples

Python Try and Except Statements – How to Handle Exceptions in Python

When coding in Python, you can often anticipate runtime errors even in a syntactically and logically correct program. These errors can be caused by invalid inputs or some predictable inconsistencies.

In Python, you can use the try and the except blocks to handle most of these errors as exceptions all the more gracefully.

In this tutorial, you’ll learn the general syntax of try and except. Then we’ll proceed to code simple examples, discuss what can go wrong, and provide corrective measures using try and except blocks.

Syntax of Python Try and Except Blocks

Let’s start by understanding the syntax of the try and except statements in Python. The general template is shown below:

try:
	# There can be errors in this block
    
except <error type>:
	# Do this to handle exception;
	# executed if the try block throws an error
    
else:
	# Do this if try block executes successfully without errors
   
finally:
	# This block is always executed

Let’s look at what the different blocks are used for:

  • The try block is the block of statements you’d like to try executing. However, there may be runtime errors due to an exception, and this block may fail to work as intended.
  • The except block is triggered when the try block fails due to an exception. It contains a set of statements that often give you some context on what went wrong inside the try block.
  • You should always mention the type of error that you intend to catch as exception inside the except block, denoted by the placeholder <error type> in the above snippet.
  • You might as well use except without specifying the <error type>. But, this is not a recommended practice as you’re not accounting for the different types of errors that can occur.

In trying to execute the code inside the try block, there’s also a possibility for multiple errors to occur.

For example, you may be accessing a list using an index that’s way out of range, using a wrong dictionary key, and trying to open a file that does not exist — all inside the try block.

In this case, you may run into IndexError, KeyError, and FileNotFoundError. And you have to add as many except blocks as the number of errors that you anticipate, one for each type of error.

  • The else block is triggered only if the try block is executed without errors. This can be useful when you’d like to take a follow-up action when the try block succeeds. For example, if you try and open a file successfully, you may want to read its content.
  • The finally block is always executed, regardless of what happens in the other blocks. This is useful when you’d like to free up resources after the execution of a particular block of code.

Note: The else and finally blocks are optional. In most cases, you can use only the try block to try doing something, and catch errors as exceptions inside the except block.

Over the next few minutes, you’ll use what you’ve learned thus far to handle exceptions in Python. Let’s get started.

How to Handle a ZeroDivisionError in Python

Consider the function divide() shown below. It takes two arguments – num and div – and returns the quotient of the division operation num/div.

def divide(num,div):
  return num/div

▶ Calling the function with different numbers returns results as expected:

res = divide(100,8)
print(res)

# Output
12.5

res = divide(568,64)
print(res)

# Output
8.875

This code works fine until you try dividing by zero:

divide(27,0)

You see that the program crashes throwing a ZeroDivisionError:

# Output
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-19-932ea024ce43> in <module>()
----> 1 divide(27,0)

<ipython-input-1-c98670fd7a12> in divide(num, div)
      1 def divide(num,div):
----> 2   return num/div

ZeroDivisionError: division by zero

You can handle this division by zero as an exception by doing the following:

  • In the try block, place a call to the divide() function. In essence, you’re trying to divide num by div.
  • Handle the case when div is 0 as an exception inside the except block.
  • In this example, you can except ZeroDivisionError by printing a message informing the user that they tried dividing by zero.

This is shown in the code snippet below:

try:
    res = divide(num,div)
    print(res)
except ZeroDivisionError:
    print("You tried to divide by zero :( ")

With a valid input, the code still works fine.

divide(10,2)
# Output
5.0

When you try diving by zero, you’re notified of the exception that occurs, and the program ends gracefully.

divide(10,0)
# Output
You tried to divide by zero :(

How to Handle a TypeError in Python

In this section, you’ll see how you can use try and except to handle a TypeError in Python.

▶ Consider the following function add_10() that takes in a number as the argument, adds 10 to it, and returns the result of this addition.

def add_10(num):
  return num + 10

You can call the function add_10() with any number and it’ll work fine, as shown below:

result = add_10(89)
print(result)

#Output
99

Now try calling add_10() with "five" instead of 5.

add_10("five")

You’ll notice that your program crashes with the following error message:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-9844e949c84e> in <module>()
----> 1 add_10("five")

<ipython-input-13-2e506d74d919> in add_10(num)
      1 def add_10(num):
----> 2   return num + 10

TypeError: can only concatenate str (not "int") to str

The error message TypeError: can only concatenate str (not "int") to str explains that you can only concatenate two strings, and not add an integer to a string.

Now, you have the following:

  • Given a number my_num, try calling the function add_10() with my_num as the argument. If the argument is of valid type, there’s no exception
  • Otherwise, the except block corresponding to the TypeError is triggered, notifying the user that the argument is of invalid type.

This is explained below:

my_num = "five"
try:
  result = add_10(my_num)
  print(result)
except TypeError:
  print("The argument `num` should be a number")

Since you’ve now handled TypeError as an exception, you’re only informed that the argument is of invalid type.

The argument `num` should be a number

How to Handle an IndexError in Python

If you’ve worked with Python lists, or any Python iterable before, you’ll have probably run into IndexError.

This is because it’s often difficult to keep track of all changes to iterables. And you may be trying to access an item at an index that’s not valid.

▶ In this example, the list my_list has 4 items. The valid indices are 0, 1, 2, and 3, and -1, -2, -3, -4 if you use negative indexing.

As 2 is a valid index, you see that the item at index 2, which is C++, is printed out:

my_list = ["Python","C","C++","JavaScript"]
print(my_list[2])

#Output
C++

If you try accessing an item at index that’s outside the range of valid indices, you’ll run into an IndexError:

print(my_list[4])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-7-437bc6501dea> in <module>()
      1 my_list = ["Python","C","C++","JavaScript"]
----> 2 print(my_list[4])

IndexError: list index out of range

If you’re familiar with the pattern, you’ll now use try and except to handle index errors.

▶ In the code snippet below, you try accessing the item at the index specified by search_idx.

search_idx = 3
try:
  print(my_list[search_idx])
except IndexError:
  print("Sorry, the list index is out of range")

Here, the search_idx (3) is a valid index, and the item at the particular index is printed out:

JavaScript

If the search_idx is outside the valid range for indices, the except block catches the IndexError as an exception, and there are no more long error messages. 🙂

search_idx = 4
try:
  print(my_list[search_idx])
except IndexError:
  print("Sorry, the list index is out of range")

Rather, the message that the search_idx is out of the valid range of indices is displayed:

Sorry, the list index is out of range

How to Handle a KeyError in Python

You have likely run into KeyError when working with Python dictionaries

▶ Consider this example where you have a dictionary my_dict.

my_dict ={"key1":"value1","key2":"value2","key3":"value3"}
search_key = "non-existent key"
print(my_dict[search_key])
  • The dictionary my_dict has 3 key-value pairs, "key1:value1", "key2:value2", and "key3:value3"
  • Now, you try to tap into the dictionary and access the value corresponding to the key "non-existent key".

As expected, you’ll get a KeyError:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-2-2a61d404be04> in <module>()
      1 my_dict ={"key1":"value1","key2":"value2","key3":"value3"}
      2 search_key = "non-existent key"
----> 3 my_dict[search_key]

KeyError: 'non-existent key'

You can handle KeyError in almost the same way you handled IndexError.

  • You can try accessing the value corresponding to the key specified by the search_key.
  • If search_key is indeed a valid key, the corresponding value is printed out.
  • If you run into an exception because of a non-existent key, you use the except block to let the user know.

This is explained in the code snippet below:

try:
  print(my_dict[search_key])
except KeyError:
  print("Sorry, that's not a valid key!")
Sorry, that's not a valid key!

▶ If you want to provide additional context such as the name of the invalid key, you can do that too. It’s possible that the key was misspelled which made it invalid. In this case, letting the user know the key used will probably help them fix the typo.

You can do this by catching the invalid key as <error_msg> and use it in the message printed when the exception occurs:

try:
  print(my_dict[search_key])
except KeyError as error_msg:
  print(f"Sorry,{error_msg} is not a valid key!")

▶ Notice how the name of the key is also printed out:

Sorry,'non-existent key' is not a valid key!

How to Handle a FileNotFoundError in Python

Another common error that occurs when working with files in Python is the FileNotFoundError.

▶ In the following example, you’re trying to open the file my_file.txt by specifying its path to the function open(). And you’d like to read the file and print out the contents of the file.

However, you haven’t yet created the file in the specified location.

If you try running the code snippet below, you’ll get a FileNotFoundError:

my_file = open("/content/sample_data/my_file.txt")
contents = my_file.read()
print(contents)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-4-4873cac1b11a> in <module>()
----> 1 my_file = open("my_file.txt")

FileNotFoundError: [Errno 2] No such file or directory: 'my_file.txt'

And using try and except, you can do the following:

  • Try opening the file in the try block.
  • Handle FileNotFoundError in the except block by letting the user know that they tried to open a file that doesn’t exist.
  • If the try block succeeds, and the file does exist, read and print out the contents of the file.
  • In the finally block, close the file so that there’s no wastage of resources. Recall how the file will be closed regardless of what happens in the file opening and reading steps.
try:
  my_file = open("/content/sample_data/my_file.txt")
except FileNotFoundError:
  print(f"Sorry, the file does not exist")
else:
  contents = my_file.read()
  print(contents)
finally:
  my_file.close()

Notice how you’ve handled the error as an exception and the program ends gracefully displaying the message below:

Sorry, the file does not exist

▶ Let’s consider the case in which the else block is triggered. The file my_file.txt is now present at the path mentioned earlier.

image-77

And here’s what the file my_file.txt contains:

image-78

Now, re-running the earlier code snippet works as expected.

This time, the file my_file.txt is present, the else block is triggered and its contents are printed out, as shown below:

image-80

I hope this clarifies how you can handle exceptions when working with files.

Conclusion

In this tutorial, you’ve learned how you can use try and except statements in Python to handle exceptions.

You coded examples to understand what types of exception may occur and how you can use except to catch the most common errors.

Hope you enjoyed this tutorial. Happy coding! Until next time :)



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

В этом руководстве мы расскажем, как обрабатывать исключения в Python с помощью try и except. Рассмотрим общий синтаксис и простые примеры, обсудим, что может пойти не так, и предложим меры по исправлению положения.

Зачастую разработчик может предугадать возникновение ошибок при работе даже синтаксически и логически правильной программы. Эти ошибки могут быть вызваны неверными входными данными или некоторыми предсказуемыми несоответствиями.

Для обработки большей части этих ошибок как исключений в Python есть блоки try и except.

Для начала разберем синтаксис операторов try и except в Python. Общий шаблон представлен ниже:

try:
	# В этом блоке могут быть ошибки
    
except <error type>:
	# Сделай это для обработки исключения;
	# выполняется, если блок try выбрасывает ошибку
    
else:
	# Сделай это, если блок try выполняется успешно, без ошибок
   
finally:
	# Этот блок выполняется всегда

Давайте посмотрим, для чего используются разные блоки.

Блок try

Блок try — это блок кода, который вы хотите попробовать выполнить. Однако во время выполнения из-за какого-нибудь исключения могут возникнуть ошибки. Поэтому этот блок может не работать должным образом.

Блок except

Блок except запускается, когда блок try не срабатывает из-за исключения. Инструкции в этом блоке часто дают некоторый контекст того, что пошло не так внутри блока try.

Если собираетесь перехватить ошибку как исключение, в блоке except нужно обязательно указать тип этой ошибки. В приведенном выше сниппете место для указания типа ошибки обозначено плейсхолдером <error type> .

except можно использовать и без указания типа ошибки. Но лучше так не делать. При таком подходе не учитывается, что возникающие ошибки могут быть разных типов. То есть вы будете знать, что что-то пошло не так, но что именно произошло, какая была ошибка — вам будет не известно.

При попытке выполнить код внутри блока try также существует вероятность возникновения нескольких ошибок.

Например, вы можете попытаться обратиться к элементу списка по индексу, выходящему за пределы допустимого диапазона, использовать неправильный ключ словаря и попробовать открыть несуществующий файл – и все это внутри одного блока try.

В результате вы можете столкнуться с IndexError, KeyError и FileNotFoundError. В таком случае нужно добавить столько блоков except, сколько ошибок ожидается – по одному для каждого типа ошибки.

Блок else

Блок else запускается только в том случае, если блок try выполняется без ошибок. Это может быть полезно, когда нужно выполнить ещё какие-то действия после успешного выполнения блока try. Например, после успешного открытия файла вы можете прочитать его содержимое.

Блок finally

Блок finally выполняется всегда, независимо от того, что происходит в других блоках. Это полезно, когда вы хотите освободить ресурсы после выполнения определенного блока кода.

Примечание: блоки else и finally не являются обязательными. В большинстве случаев вы можете использовать только блок try, чтобы что-то сделать, и перехватывать ошибки как исключения внутри блока except.

[python_ad_block]

Итак, теперь давайте используем полученные знания для обработки исключений в Python. Приступим!

Обработка ZeroDivisionError

Рассмотрим функцию divide(), показанную ниже. Она принимает два аргумента – num и div – и возвращает частное от операции деления num/div.

def divide(num,div):
    return num/div

Вызов функции с разными аргументами возвращает ожидаемый результат:

res = divide(100,8)
print(res)

# Output
# 12.5

res = divide(568,64)
print(res)

# Output
# 8.875

Этот код работает нормально, пока вы не попробуете разделить число на ноль:

divide(27,0)

Вы видите, что программа выдает ошибку ZeroDivisionError:

# Output
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-19-932ea024ce43> in <module>()
----> 1 divide(27,0)

<ipython-input-1-c98670fd7a12> in divide(num, div)
      1 def divide(num,div):
----> 2   return num/div

ZeroDivisionError: division by zero

Можно обработать деление на ноль как исключение, выполнив следующие действия:

  1. В блоке try поместите вызов функции divide(). По сути, вы пытаетесь разделить num на div (try в переводе с английского — «пытаться», — прим. перев.).
  2. В блоке except обработайте случай, когда div равен 0, как исключение.
  3. В результате этих действий при делении на ноль больше не будет выбрасываться ZeroDivisionError. Вместо этого будет выводиться сообщение, информирующее пользователя, что он попытался делить на ноль.

Вот как все это выглядит в коде:

try:
    res = divide(num,div)
    print(res)
except ZeroDivisionError:
    print("You tried to divide by zero :( ")

При корректных входных данных наш код по-прежнему работает великолепно:

divide(10,2)
# Output
# 5.0

Когда же пользователь попытается разделить на ноль, он получит уведомление о возникшем исключении. Таким образом, программа завершается корректно и без ошибок.

divide(10,0)
# Output
# You tried to divide by zero :(

Обработка TypeError

В этом разделе мы разберем, как использовать try и except для обработки TypeError в Python.

Рассмотрим функцию add_10(). Она принимает число в качестве аргумента, прибавляет к нему 10 и возвращает результат этого сложения.

def add_10(num):
    return num + 10

Вы можете вызвать функцию add_10() с любым числом, и она будет работать нормально, как показано ниже:

result = add_10(89)
print(result)

# Output
# 99

Теперь попробуйте вызвать функцию add_10(), передав ей в качестве аргумента не число, а строку.

add_10 ("five")

Ваша программа вылетит со следующим сообщением об ошибке:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-9844e949c84e> in <module>()
----> 1 add_10("five")

<ipython-input-13-2e506d74d919> in add_10(num)
      1 def add_10(num):
----> 2   return num + 10

TypeError: can only concatenate str (not "int") to str

Сообщение об ошибке TypeError: can only concatenate str (not "int") to str говорит о том, что можно сложить только две строки, а не добавить целое число к строке.

Обработаем TypeError:

  • В блок try мы помещаем вызов функции add_10() с my_num в качестве аргумента. Если аргумент допустимого типа, исключений не возникнет.
  • В противном случае срабатывает блок except, в который мы помещаем вывод уведомления для пользователя о том, что аргумент имеет недопустимый тип.

Это показано ниже:

my_num = "five"
try:
    result = add_10(my_num)
    print(result)
except TypeError:
    print("The argument `num` should be a number")

Поскольку теперь вы обработали TypeError как исключение, при передаче невалидного аргумента ошибка не возникает. Вместо нее выводится сообщение, что аргумент имеет недопустимый тип.

The argument `num` should be a number

Обработка IndexError

Если вам приходилось работать со списками или любыми другими итерируемыми объектами, вы, вероятно, сталкивались с IndexError.

Это связано с тем, что часто бывает сложно отслеживать все изменения в итерациях. И вы можете попытаться получить доступ к элементу по невалидному индексу.

В этом примере список my_list состоит из 4 элементов. Допустимые индексы — 0, 1, 2 и 3 и -1, -2, -3, -4, если вы используете отрицательную индексацию.

Поскольку 2 является допустимым индексом, вы видите, что элемент с этим индексом (C++) распечатывается:

my_list = ["Python","C","C++","JavaScript"]
print(my_list[2])

# Output
# C++

Но если вы попытаетесь получить доступ к элементу по индексу, выходящему за пределы допустимого диапазона, вы столкнетесь с IndexError:

print(my_list[4])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-7-437bc6501dea> in <module>()
      1 my_list = ["Python","C","C++","JavaScript"]
----> 2 print(my_list[4])

IndexError: list index out of range

Теперь вы уже знакомы с шаблоном, и вам не составит труда использовать try и except для обработки данной ошибки.

В приведенном ниже фрагменте кода мы пытаемся получить доступ к элементу по индексу search_idx.

search_idx = 3
try:
    print(my_list[search_idx])
except IndexError:
    print("Sorry, the list index is out of range")

Здесь search_idx = 3 является допустимым индексом, поэтому в результате выводится соответствующий элемент — JavaScript.

Если search_idx находится за пределами допустимого диапазона индексов, блок except перехватывает IndexError как исключение, и больше нет длинных сообщений об ошибках.

search_idx = 4
try:
    print(my_list[search_idx])
except IndexError:
    print("Sorry, the list index is out of range")

Вместо этого отображается сообщение о том, что search_idx находится вне допустимого диапазона индексов:

Sorry, the list index is out of range

Обработка KeyError

Вероятно, вы уже сталкивались с KeyError при работе со словарями в Python.

Рассмотрим следующий пример, где у нас есть словарь my_dict.

my_dict ={"key1":"value1","key2":"value2","key3":"value3"}
search_key = "non-existent key"
print(my_dict[search_key])

В словаре my_dict есть 3 пары «ключ-значение»: key1:value1, key2:value2 и key3:value3.

Теперь попытаемся получить доступ к значению, соответствующему несуществующему ключу non-existent key.

Как и ожидалось, мы получим KeyError:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-2-2a61d404be04> in <module>()
      1 my_dict ={"key1":"value1","key2":"value2","key3":"value3"}
      2 search_key = "non-existent key"
----> 3 my_dict[search_key]

KeyError: 'non-existent key'

Вы можете обработать KeyError почти так же, как и IndexError.

  • Пробуем получить доступ к значению, которое соответствует ключу, определенному search_key.
  • Если search_key — валидный ключ, мы распечатываем соответствующее значение.
  • Если ключ невалиден и возникает исключение — задействуется блок except, чтобы сообщить об этом пользователю.

Все это можно видеть в следующем коде:

try:
    print(my_dict[search_key])
except KeyError:
    print("Sorry, that's not a valid key!")

# Output:
# Sorry, that's not a valid key!

Если вы хотите предоставить дополнительный контекст, например имя невалидного ключа, это тоже можно сделать. Возможно, ключ оказался невалидным из-за ошибки в написании. Если вы укажете этот ключ в сообщении, это поможет пользователю исправить опечатку.

Вы можете сделать это, перехватив невалидный ключ как <error_msg> и используя его в сообщении, которое печатается при возникновении исключения:

try:
    print(my_dict[search_key])
except KeyError as error_msg:
    print(f"Sorry,{error_msg} is not a valid key!")

Обратите внимание, что теперь в сообщении об ошибки указано также и имя несуществующего ключа:

Sorry, 'non-existent key' is not a valid key!

Обработка FileNotFoundError

При работе с файлами в Python часто возникает ошибка FileNotFoundError.

В следующем примере мы попытаемся открыть файл my_file.txt, указав его путь в функции open(). Мы хотим прочитать файл и вывести его содержимое.

Однако мы еще не создали этот файл в указанном месте.

my_file = open("/content/sample_data/my_file.txt")
contents = my_file.read()
print(contents)

Поэтому, попытавшись запустить приведенный выше фрагмент кода, мы получим FileNotFoundError:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-4-4873cac1b11a> in <module>()
----> 1 my_file = open("my_file.txt")

FileNotFoundError: [Errno 2] No such file or directory: 'my_file.txt'

А с помощью try и except мы можем сделать следующее:

  • Попробуем открыть файл в блоке try.
  • Обработаем FileNotFoundError в блоке except, сообщив пользователю, что он попытался открыть несуществующий файл.
  • Если блок try завершается успешно и файл действительно существует, прочтем и распечатаем содержимое.
  • В блоке finally закроем файл, чтобы не терять ресурсы. Файл будет закрыт независимо от того, что происходило на этапах открытия и чтения.
try:
    my_file = open("/content/sample_data/my_file.txt")
except FileNotFoundError:
    print(f"Sorry, the file does not exist")
else:
    contents = my_file.read()
    print(contents)
finally:
    my_file.close()

Обратите внимание: мы обработали ошибку как исключение, и программа завершает работу, отображая следующее сообщение:

Sorry, the file does not exist

Теперь рассмотрим случай, когда срабатывает блок else. Файл my_file.txt теперь присутствует по указанному ранее пути.

Вот содержимое этого файла:

Теперь повторный запуск нашего кода работает должным образом.

На этот раз файл my_file.txt присутствует, поэтому запускается блок else и содержимое распечатывается, как показано ниже:

Надеемся, теперь вы поняли, как обрабатывать исключения при работе с файлами.

Заключение

В этом руководстве мы рассмотрели, как обрабатывать исключения в Python с помощью try и except.

Также мы разобрали на примерах, какие типы исключений могут возникать и как при помощи except ловить наиболее распространенные ошибки.

Надеемся, вам понравился этот урок. Успехов в написании кода!

Перевод статьи «Python Try and Except Statements – How to Handle Exceptions in Python».

In the last tutorial, we learned about Python exceptions. We know that exceptions abnormally terminate the execution of a program.

This is why it is important to handle exceptions. In Python, we use the try...except block


Python try…except Block

The try...except block is used to handle exceptions in Python. Here’s the syntax of try...except block:

try:
    # code that may cause exception
except:
    # code to run when exception occurs

Here, we have placed the code that might generate an exception inside the try block. Every try block is followed by an except block.

When an exception occurs, it is caught by the except block. The except block cannot be used without the try block.

Example: Exception Handling Using try…except

try:
    numerator = 10
    denominator = 0

    result = numerator/denominator

    print(result)
except:
    print("Error: Denominator cannot be 0.")

# Output: Error: Denominator cannot be 0. 

In the example, we are trying to divide a number by 0. Here, this code generates an exception.

To handle the exception, we have put the code, result = numerator/denominator inside the try block. Now when an exception occurs, the rest of the code inside the try block is skipped.

The except block catches the exception and statements inside the except block are executed.

If none of the statements in the try block generates an exception, the except block is skipped.


Catching Specific Exceptions in Python

For each try block, there can be zero or more except blocks. Multiple except blocks allow us to handle each exception differently.

The argument type of each except block indicates the type of exception that can be handled by it. For example,

try:
    
    even_numbers = [2,4,6,8]
    print(even_numbers[5])

except ZeroDivisionError:
    print("Denominator cannot be 0.")
    
except IndexError:
    print("Index Out of Bound.")

# Output: Index Out of Bound

In this example, we have created a list named even_numbers.

Since the list index starts from 0, the last element of the list is at index 3. Notice the statement,

print(even_numbers[5])

Here, we are trying to access a value to the index 5. Hence, IndexError exception occurs.

When the IndexError exception occurs in the try block,

  • The ZeroDivisionError exception is skipped.
  • The set of code inside the IndexError exception is executed.

Python try with else clause

In some situations, we might want to run a certain block of code if the code block inside try runs without any errors.

For these cases, you can use the optional else keyword with the try statement.

Let’s look at an example:

# program to print the reciprocal of even numbers

try:
    num = int(input("Enter a number: "))
    assert num % 2 == 0
except:
    print("Not an even number!")
else:
    reciprocal = 1/num
    print(reciprocal)

Output

If we pass an odd number:

Enter a number: 1
Not an even number!

If we pass an even number, the reciprocal is computed and displayed.

Enter a number: 4
0.25

However, if we pass 0, we get ZeroDivisionError as the code block inside else is not handled by preceding except.

Enter a number: 0
Traceback (most recent call last):
  File "<string>", line 7, in <module>
    reciprocal = 1/num
ZeroDivisionError: division by zero

Note: Exceptions in the else clause are not handled by the preceding except clauses.


Python try…finally

In Python, the finally block is always executed no matter whether there is an exception or not.

The finally block is optional. And, for each try block, there can be only one finally block.

Let’s see an example,

try:
    numerator = 10
    denominator = 0

    result = numerator/denominator

    print(result)
except:
    print("Error: Denominator cannot be 0.")
    
finally:
    print("This is finally block.")

Output

Error: Denominator cannot be 0.
This is finally block.

In the above example, we are dividing a number by 0 inside the try block. Here, this code generates an exception.

The exception is caught by the except block. And, then the finally block is executed.

Понравилась статья? Поделить с друзьями:
  • Python throw error
  • Python tab space error
  • Python systemerror error return without exception set
  • Python syntax error non utf 8
  • Python syntax error meme