Raise error питон

In this beginner tutorial you'll learn what exceptions are good for in Python. You'll see how to raise exceptions and how to handle them with "try/except" blocks.

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

Introduction

Software applications don’t run perfectly all the time. Despite intensive debugging and multiple testing levels, applications still fail. Bad data, broken network connectivity, corrupted databases, memory pressures, and unexpected user inputs can all prevent an application from performing normally. When such an event occurs, and the app is unable to continue its normal flow, this is known as an exception. And it’s your application’s job—and your job as a coder—to catch and handle these exceptions gracefully so that your app keeps working.

Install the Python SDK to identify and fix exceptions

What Are Python Exceptions?

Exceptions in Python applications can happen for many of the reasons stated above and more; and if they aren’t handled well, these exceptions can cause the program to crash, causing data loss, or worse, corrupted data. As a Python developer, you need to think about possible exception situations and include error handling in your code.

Fortunately, Python comes with a robust error handling framework. Using structured exception handling and a set of pre-defined exceptions, Python programs can determine the error type at run time and act accordingly. These can include actions like taking an alternate path, using default values, or prompting for correct input.

This article will show you how to raise exceptions in your Python code and how to address exceptions.

Difference Between Python Syntax Errors and Python Exceptions

Before diving in, it’s important to understand the two types of unwanted conditions in Python programming—syntax error and exception.

The syntax error exception occurs when the code does not conform to Python keywords, naming style, or programming structure. The interpreter sees the invalid syntax during its parsing phase and raises a SyntaxError exception. The program stops and fails at the point where the syntax error happened. That’s why syntax errors are exceptions that can’t be handled.

Here’s an example code block with a syntax error (note the absence of a colon after the “if” condition in parentheses):

a = 10
b = 20

if (a < b)
    print('a is less than b')

c = 30
print(c)

The interpreter picks up the error and points out the line number. Note how it doesn’t proceed after the syntax error:

File "test.py", line 4
    if (a < b)
             ^
SyntaxError: invalid syntax

Process finished with exit code 1

On the other hand, an exception happens when the code has no syntax error but encounters other error situations. These conditions can be addressed within the code—either in the current function or in the calling stack. In this sense, exceptions are not fatal. A Python program can continue to run if it gracefully handles the exception.

Here is an example of a Python code that doesn’t have any syntax errors. It’s trying to run an arithmetic operation on two string variables:

a = 'foo'
b = 'bar'
print(a % b)

The exception raised is TypeError:

Traceback (most recent call last):
  File "test.py", line 4, in 
    print(a % b)
TypeError: not all arguments converted during string formatting

Process finished with exit code 1

Python throws the TypeError exception when there are wrong data types. Similar to TypeError, there are several built-in exceptions like:

  1. ModuleNotFoundError
  2. ImportError
  3. MemoryError
  4. OSError
  5. SystemError
  6. … And so on

You can refer to the Python documentation for a full list of exceptions.

How to Throw an Exception in Python

Sometimes you want Python to throw a custom exception for error handling. You can do this by checking a condition and raising the exception, if the condition is True. The raised exception typically warns the user or the calling application.

You use the “raise” keyword to throw a Python exception manually. You can also add a message to describe the exception

Here is a simple example: Say you want the user to enter a date. The date has to be either today or in the future. If the user enters a past date, the program should raise an exception:

Python Throw Exception Example

from datetime import datetime

current_date = datetime.now()
print("Current date is: " + current_date.strftime('%Y-%m-%d'))

dateinput = input("Enter date in yyyy-mm-dd format: ")
# We are not checking for the date input format here
date_provided = datetime.strptime(dateinput, '%Y-%m-%d')
print("Date provided is: " + date_provided.strftime('%Y-%m-%d'))

if date_provided.date() < current_date.date():
    raise Exception("Date provided can't be in the past")

To test the code, we enter a date older than the current date. The “if” condition evaluates to true and raises the exception:

Current date is: 2021-01-24
Enter date in yyyy-mm-dd format: 2021-01-22
Date provided is: 2021-01-22
Traceback (most recent call last):
  File "test.py", line 13, in 
    raise Exception("Date provided can't be in the past")
Exception: Date provided can't be in the past

Process finished with exit code 1

Instead of raising a generic exception, we can specify a type for it, too:

if (date_provided.date() < current_date.date()):
    raise ValueError("Date provided can't be in the past")

With a similar input as before, Python will now throw this exception:

raise ValueError("Date provided can't be in the past")
ValueError: Date provided can't be in the past

Using AssertionError in Python Exception Throwing

Another way to raise an exception is to use assertion. With assertion, you assert a condition to be true before running a statement. If the condition evaluates to true, the statement runs, and the control continues to the next statement. However, if the condition evaluates to false, the program throws an AssertionError. The diagram below shows the logical flow:

Use AssertionError to raise and throw an exception in Python

Using AssertionError, we can rewrite the code snippet in the last section like this:

from datetime import datetime

current_date = datetime.now()
print("Current date is: " + current_date.strftime('%Y-%m-%d'))

dateinput = input("Enter date in yyyy-mm-dd format: ")
# We are not checking for the date input format here
date_provided = datetime.strptime(dateinput, '%Y-%m-%d')
print("Date provided is: " + date_provided.strftime('%Y-%m-%d'))

assert(date_provided.date() >= current_date.date()), "Date provided can't be in the past"

Note how we removed the “if” condition and are now asserting that the date provided is greater than or equal to the current date. When inputting an older date, the AssertionError displays:

Current date is: 2021-01-24
Enter date in yyyy-mm-dd format: 2021-01-23
Traceback (most recent call last):
Date provided is: 2021-01-23
  File "test.py", line 12, in 
    assert(date_provided.date() >= current_date.date()), "Date provided can't be in the past"
AssertionError: Date provided can't be in the past

Process finished with exit code 1

Catching Python Exceptions with Try-Except

Now that you understand how to throw exceptions in Python manually, it’s time to see how to handle those exceptions. Most modern programming languages use a construct called “try-catch” for exception handling. With Python, its basic form is “try-except”. The try-except block looks like this:

Python Try Catch Exception Example


...
try:
    <--program code-->
except:
    <--exception handling code-->
<--program code-->
...

Here, the program flow enters the “try” block. If there is an exception, the control jumps to the code in the “except” block. The error handling code you put in the “except” block depends on the type of error you think the code in the “try” block may encounter.

Here’s an example of Python’s “try-except” (often mistakenly referred to as “try-catch-exception”). Let’s say we want our code to run only if the Python version is 3. Using a simple assertion in the code looks like this:

import sys
assert (sys.version_info[0] == 3), "Python version must be 3"

If the of Python version is not 3, the error message looks like this:

Traceback (most recent call last):
  File "test.py", line 2, in 
    assert (sys.version_info[0] == 3), "Python version must be 3"
AssertionError: Python version must be 3

Process finished with exit code 1

Instead of letting the program fail with an unhandled exception and showing an ugly error message, we could use a try-except block for a graceful exit.

import sys
try:
    assert (sys.version_info[0] == 3), "Python version must be 3"
except Exception as e:
    print(e)
    rollbar.report_exc_info()

Now, the error message is much cleaner:

Python version must be 3

The “except” keyword in the construct also accepts the type of error you want to handle. To illustrate this, let’s go back to our date script from the last section. In that script, we assumed the user will enter a date in “YYYY-MM-DD” format. However, as a developer, you should cater to any type of erroneous data instead of depending on the user. For example, some exception scenarios can be:

  1. No date entered (blank)
  2. Text entered
  3. Number entered
  4. Time entered
  5. Special characters entered
  6. Different date format entered (such as “dd/mm/yyyy”)

To address all these conditions, we can rewrite the code block as shown below. This will catch any ValueError exception raised when meeting any of the above conditions:

from datetime import datetime

current_date = datetime.now()
print("Current date is: " + current_date.strftime('%Y-%m-%d'))

dateinput = input("Enter date in yyyy-mm-dd format: ")

try:
    date_provided = datetime.strptime(dateinput, '%Y-%m-%d')
except ValueError as e:
    print(e)
    rollbar.report_exc_info()
    exit()

print("Date provided is: " + date_provided.strftime('%Y-%m-%d'))
assert(date_provided.date() >= current_date.date()), "Date provided can't be in the past"

In this case, the program will exit gracefully if the date isn’t correctly formatted.

You can include multiple “except” blocks for the “try” block to trap different types of exceptions. Each “except” block will address a specific type of error:

...
try:
    <--program code-->
except <--Exception Type 1-->:
    <--exception handling code-->
except <--Exception Type 2-->:
    <--exception handling code-->
except <--Exception Type 3-->:
    <--exception handling code-->
...

Here’s a very simple example:

num0 = 10

try:
    num1 = input("Enter 1st number:")
    num2 = input("Enter 2nd number:")
    result = (int(num1) * int(num2))/(num0 * int(num2))
except ValueError as ve:
    print(ve)
    rollbar.report_exc_info()
    exit()
except ZeroDivisionError as zde:
    print(zde)
    rollbar.report_exc_info()
    exit()
except TypeError as te:
    print(te)
    rollbar.report_exc_info()
    exit()
except:
    print('Unexpected Error!')
    rollbar.report_exc_info()
    exit()

print(result)

We can test this program with different values:

Enter 1st number:1
Enter 2nd number:0
division by zero

Enter 1st number:
Enter 2nd number:6
invalid literal for int() with base 10: ''

Enter 1st number:12.99
Enter 2nd number:33
invalid literal for int() with base 10: '12.99'

Catching Python Exceptions with Try-Except-Else

The next element in the Python “try-except” construct is “else”:

Python Try Except Else Example

...
try:
    <--program code-->
except <--Exception Type 1-->:
    <--exception handling code-->
except <--Exception Type 2-->:
    <--exception handling code-->
except <--Exception Type 3-->:
    <--exception handling code-->
...
else:
    <--program code to run if "try" block doesn't encounter any error-->
...

The “else” block runs if there are no exceptions raised from the “try” block. Looking at the code structure above, you can see the “else” in Python exception handling works almost the same as an “if-else” construct

To show how “else” works, we can slightly modify the arithmetic script’s code from the last section. If you look at the script, you will see we calculated the variable value of “result” using an arithmetic expression. Instead of putting this in the “try” block, you can move it to an “else” block. That way, the exception blocks any error raised while converting the input values to integers. And if there are no exceptions, the “else” block will perform the actual calculation:

num0 = 10

try:
    num1 = int(input("Enter 1st number:"))
    num2 = int(input("Enter 2nd number:"))
except ValueError as ve:
    print(ve)
    rollbar.report_exc_info()
    exit()
except ZeroDivisionError as zde:
    print(zde)
    rollbar.report_exc_info()
    exit()
except TypeError as te:
    print(te)
    rollbar.report_exc_info()
    exit()
except:
    print('Unexpected Error!')
    rollbar.report_exc_info()
    exit()
else:
    result = (num1 * num2)/(num0 * num2)
    print(result)

Using simple integers as input values runs the “else” block code:

Enter 1st number:2
Enter 2nd number:3
0.2

And using erroneous data like empty values, decimal numbers, or strings cause the corresponding “except” block to run and skip the “else” block:

Enter 1st number:s
invalid literal for int() with base 10: 's'

Enter 1st number:20
Enter 2nd number:
invalid literal for int() with base 10: ''

Enter 1st number:5
Enter 2nd number:6.4
invalid literal for int() with base 10: '6.4'

However, there’s still a possibility of unhandled exceptions when the “else” block runs:

Enter 1st number:1
Enter 2nd number:0
Traceback (most recent call last):
  File "test.py", line 19, in 
    result = (num1 * num2)/(num0 * num2)
ZeroDivisionError: division by zero

As you can see, both inputs are integers (1 and 0), and the “try” block successfully converts them to integers. When the “else” block runs, we see the exception.

So how do you handle errors in the “else” block? You guessed that right—you can use another “try-except-else” block within the outer “else” block:

Enter 1st number:1
Enter 2nd number:0
division by zero

Catching Python Exceptions with Try-Except-Else-Finally

Finally, we have the last optional block in Python error handling. And it’s literally called “finally”:

Python Try Finally Example

...
try:
    <--program code-->
except <--Exception Type 1-->:
    <--exception handling code-->
except <--Exception Type 2-->:
    <--exception handling code-->
except <-->Exception Type 3-->>:
    <--exception handling code-->
...
else:
    <--program code to run if "try" block doesn't encounter any error-->
finally:
    <--program code that runs regardless of errors in the "try" or "else" block-->

The “finally” block runs whether or not the “try” block’s code raises an exception. If there’s an exception, the code in the corresponding “except” block will run, and then the code in the “finally” block will run. If there are no exceptions, the code in the “else” block will run (if there’s an “else” block), and then the code in the “finally” block will run.

Since the code in the “finally” block always runs, you want to keep your “clean up” codes here, such as:

  1. Writing status messages to log files
  2. Resetting counters, lists, arrays
  3. Closing open files
  4. Closing database connections
  5. Resetting object variables
  6. Disconnecting from network resources
  7. … And so on

Here’s an example of using “finally”:

try:
    f = open("testfile.txt", 'r')
except FileNotFoundError as fne:
    rollbar.report_exc_info()
    print(fne)
    print('Creating file...')
    f = open("testfile.txt", 'w')
    f.write('2')
else:
    data=f.readline(1)
    print(data)
finally:
    print('Closing file')
    f.close()

Here, the “try” block tries to open a file for reading. If the file doesn’t exist, the exception block shows a warning message, creates the file, and adds a static value of “2” to it. If the file exists, the “else” block reads the first line of its content and prints that out. Finally, the “finally” block closes the file. This happens whether or not the file initially existed.

What we have discussed so far can be summarized in the flowchart below:

Python exception handling logical flow

How Rollbar Can Help Log and Track Python Errors

Rollbar is a continuous code improvement platform for software development teams. It offers an automated way to capture Python errors and failed tests in real time from all application stack layers and across all environments. This allows creating a proactive and automated response to application errors. The diagram below shows how Rollbar works:

Rollbar automated testing model

Rollbar natively works with a wide array of programming languages and frameworks, including Python. Python developers can install pyrollbar, Rollbar’s SDK for Python, using a tool like pip, importing the Rollbar class in the code, and sending Python exceptions to Rollbar. The code snippet below shows how easy it is:

import rollbar
rollbar.init('POST_SERVER_ITEM_ACCESS_TOKEN', 'dev')

try:
    # some code
except TypeError:
    rollbar.report_message('There is a data type mismatch', 'fatal')
except:
    rollbar.report_exc_info()

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing errors easier than ever. Try it today.

Raise, return, and how to never fail silently in Python.

I hear this question a lot: “Do I raise or return this error in Python?”

The right answer will depend on the goals of your application logic. You want to ensure your Python code doesn’t fail silently, saving you and your teammates from having to hunt down deeply entrenched errors.

Here’s the difference between raise and return when handling failures in Python.

When to raise

The raise statement allows the programmer to force a specific exception to occur. (8.4 Raising Exceptions)

Use raise when you know you want a specific behavior, such as:

raise TypeError("Wanted strawberry, got grape.")

Raising an exception terminates the flow of your program, allowing the exception to bubble up the call stack. In the above example, this would let you explicitly handle TypeError later. If TypeError goes unhandled, code execution stops and you’ll get an unhandled exception message.

Raise is useful in cases where you want to define a certain behavior to occur. For example, you may choose to disallow certain words in a text field:

if "raisins" in text_field:
    raise ValueError("That word is not allowed here")

Raise takes an instance of an exception, or a derivative of the Exception class. Here are all of Python’s built-in exceptions.

Raise can help you avoid writing functions that fail silently. For example, this code will not raise an exception if JAM doesn’t exist:

import os


def sandwich_or_bust(bread: str) -> str:
    jam = os.getenv("JAM")
    return bread + str(jam) + bread


s = sandwich_or_bust("U0001F35E")
print(s)
# Prints "🍞None🍞" which is not very tasty.

To cause the sandwich_or_bust() function to actually bust, add a raise:

import os


def sandwich_or_bust(bread: str) -> str:
    jam = os.getenv("JAM")
    if not jam:
        raise ValueError("There is no jam. Sad bread.")
    return bread + str(jam) + bread


s = sandwich_or_bust("U0001F35E")
print(s)
# ValueError: There is no jam. Sad bread.

Any time your code interacts with an external variable, module, or service, there is a possibility of failure. You can use raise in an if statement to help ensure those failures aren’t silent.

Raise in try and except

To handle a possible failure by taking an action if there is one, use a tryexcept statement.

try:
    s = sandwich_or_bust("U0001F35E")
    print(s)
except ValueError:
    buy_more_jam()
    raise

This lets you buy_more_jam() before re-raising the exception. If you want to propagate a caught exception, use raise without arguments to avoid possible loss of the stack trace.

If you don’t know that the exception will be a ValueError, you can also use a bare except: or catch any derivative of the Exception class with except Exception:. Whenever possible, it’s better to raise and handle exceptions explicitly.

Use else for code to execute if the try does not raise an exception. For example:

try:
    s = sandwich_or_bust("U0001F35E")
    print(s)
except ValueError:
    buy_more_jam()
    raise
else:
    print("Congratulations on your sandwich.")

You could also place the print line within the try block, however, this is less explicit.

When to return

When you use return in Python, you’re giving back a value. A function returns to the location it was called from.

While it’s more idiomatic to raise errors in Python, there may be occasions where you find return to be more applicable.

For example, if your Python code is interacting with other components that do not handle exception classes, you may want to return a message instead. Here’s an example using a tryexcept statement:

from typing import Union


def share_sandwich(sandwich: int) -> Union[float, Exception]:
    try:
        bad_math = sandwich / 0
        return bad_math
    except Exception as e:
        return e


s = share_sandwich(1)
print(s)
# Prints "division by zero"

Note that when you return an Exception class object, you’ll get a representation of its associated value, usually the first item in its list of arguments. In the example above, this is the string explanation of the exception. In some cases, it may be a tuple with other information about the exception.

You may also use return to give a specific error object, such as with HttpResponseNotFound in Django. For example, you may want to return a 404 instead of a 403 for security reasons:

if object.owner != request.user:
    return HttpResponseNotFound

Using return can help you write appropriately noisy code when your function is expected to give back a certain value, and when interacting with outside elements.

The most important part

Silent failures create some of the most frustrating bugs to find and fix. You can help create a pleasant development experience for yourself and your team by using raise and return to ensure that errors are handled in your Python code.

I write about good development practices and how to improve productivity as a software developer. You can get these tips right in your inbox by signing up below!

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

2. Обработка исключений в Python

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

3. Блоки try/except

Если код может привести к исключению, его лучше заключить в блок try. Рассмотрим на примере.

try:
    for i in range(3):
        print(3/i)
except:
    print("Деление на 0")
    print("Исключение было обработано")

Программа вывела сообщение, потому что было обработано исключение.

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

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

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

a. Несколько except в Python

У одного блока try может быть несколько блоков except. Рассмотрим примеры с несколькими вариантами обработки.

a, b = 1, 0
try:
    print(a/b)
    print("Это не будет напечатано")
    print('10'+10)
except TypeError:
    print("Вы сложили значения несовместимых типов")
except ZeroDivisionError:
    print("Деление на 0")

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

В первом примере первая инструкция приводит к ZeroDivisionError. Эта ошибка обрабатывается в блоке except, но инструкции в try после первой не исполняются. Так происходит из-за того, что после первого исключения дальнейшие инструкции просто пропускаются. И если подходящий или общий блоки except не удается найти, исключение не обрабатывается. В таком случае оставшаяся часть программы не будет запущена. Но если обработать исключение, то код после блоков except и finally исполнится. Попробуем.

a, b = 1, 0
try:
   print(a/b)
except:
   print("Вы не можете разделить на 0")
print("Будет ли это напечатано?")

Рассмотрим вывод:

Вы не можете разделить на 0
Будет ли это напечатано?

b. Несколько исключений в одном except

Можно использовать один блок except для обработки нескольких исключений. Для этого используются скобки. Без них интерпретатор вернет синтаксическую ошибку.

try:
    print('10'+10)
    print(1/0)
except (TypeError,ZeroDivisionError):
    print("Неверный ввод")
Неверный ввод

c. Общий except после всех блоков except

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

try:
    print('1'+1)
    print(sum)
    print(1/0)
except NameError:
    print("sum не существует")
except ZeroDivisionError:
    print("Вы не можете разделить на 0")
except:
    print("Что-то пошло не так...")
Что-то пошло не так...

Здесь первая инструкция блока пытается осуществить операцию конкатенации строки python с числом. Это приводит к ошибке TypeError. Как только интерпретатор сталкивается с этой проблемой, он проверяет соответствующий блок except, который ее обработает.

Отдельную инструкцию нельзя разместить между блоками try и except.

try:
    print("1")
print("2")
except:
    print("3")

Это приведет к синтаксической ошибке.

Но может быть только один общий или блок по умолчанию типа except. Следующий код вызовет ошибку «default 'except:' must be last»:

try:
    print(1/0)
except:
    raise
except:
    print("Исключение поймано")
finally:
    print("Хорошо")
print("Пока")

4. Блок finally в Python

После последнего блока except можно добавить блок finally. Он исполняет инструкции при любых условиях.

try:
    print(1/0)
except ValueError:
    print("Это ошибка значения")
finally:
    print("Это будет напечатано в любом случае.")
Это будет напечатано в любом случае.

Traceback (most recent call last):  
  File “”, line 2, in   
    print(1/0)
ZeroDivisionError: division by zero

Стоит обратить внимание, что сообщение с ошибкой выводится после исполнения блока finally. Почему же тогда просто не использовать print? Но как видно по последнему примеру, блок finally запускается даже в том случае, если перехватить исключение не удается.

А что будет, если исключение перехватывается в except?

try:
    print(1/0)
except ZeroDivisionError:
    print(2/0)
finally:
    print("Ничего не происходит")
Ничего не происходит

Traceback (most recent call last):
  File "", line 2, in 
    print(1/0)
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "", line 4, in 
    print(2/0)
ZeroDivisionError: division by zero

Как видите, код в блоке finally исполняется в любом случае.

5. Ключевое слово raise в Python

Иногда нужно будет разбираться с проблемами с помощью вызова исключения. Обычная инструкция print тут не сработает.

raise ZeroDivisionError
Traceback (most recent call last):
  File "", line 1, in 
    raise ZeroDivisionError
ZeroDivisionError

Разберемся на примере операции деления:

a,b=int(input()),int(input())  # вводим 1 затем 0
if b==0:
    raise ZeroDivisionError
Traceback (most recent call last):
  File "", line 3, in 
    raise ZeroDivisionError
ZeroDivisionError

Здесь ввод пользователя в переменные a и b конвертируется в целые числа. Затем проверяется, равна ли b нулю. Если да, то вызывается ZeroDivisionError.

Что будет, если то же самое добавить в блоки try-except? Добавим следующее в код. Если запустить его, ввести 1 и 0, будет следующий вывод:

a,b=int(input()),int(input())
try:
    if b==0:
        raise ZeroDivisionError
except:
   print("Деление на 0")
print("Будет ли это напечатано?")
1
0
Деление на 0
Будет ли это напечатано?

Рассмотрим еще несколько примеров, прежде чем двигаться дальше:

raise KeyError
Traceback (most recent call last):
  File “”, line 1, in 
    raise KeyError
KeyError

a. Raise без определенного исключения в Python

Можно использовать ключевое слово raise и не указывая, какое исключение вызвать. Оно вызовет исключение, которое произошло. Поэтому его можно использовать только в блоке except.

try:
    print('1'+1)
except:
    raise
Traceback (most recent call last):
  File “”, line 2, in 
    print(‘1’+1)
TypeError: must be str, not int

b. Raise с аргументом в Python

Также можно указать аргумент к определенному исключению в raise. Делается это с помощью дополнительных деталей исключения.

raise ValueError("Несоответствующее значение")
Traceback (most recent call last):
  File "", line 1, in 
    raise ValueError("Несоответствующее значение")
ValueError: Несоответствующее значение

6. assert в Python

Утверждение (assert) — это санитарная проверка для вашего циничного, параноидального «Я». Оно принимает инструкцию в качестве аргумента и вызывает исключение Python, если возвращается значение False. В противном случае выполняет операцию No-operation (NOP).

assert(True)
#  код работает дальше

Если бы инструкция была False?

assert(1==0)
Traceback (most recent call last):
  File “”, line 1, in 
    assert(1==0)
AssertionError

Возьмем другой пример:

try:
    print(1)
    assert 2+2==4
    print(2)
    assert 1+2==4
    print(3)
except:
    print("assert False.")
    raise
finally:
    print("Хорошо")
print("Пока")

Вывод следующий:

1
2
assert False.
Хорошо
Traceback (most recent call last):
  File “”, line 5, in 
    assert 1+2==4
AssertionError

Утверждения можно использовать для проверки валидности ввода и вывода в функции.

a. Второй аргумент для assert

Можно предоставить второй аргумент, чтобы дать дополнительную информацию о проблеме.

assert False,"Это проблема"
Traceback (most recent call last):
  File “”, line 1, in 
    assert False,”Это проблема”
AssertionError: Это проблема

7. Объявление собственных исключений Python

Наконец, рассмотрим процесс создания собственных исключений. Для этого создадим новый класс из класса Exception. Потом его можно будет вызывать как любой другой тип исключения.

class MyError(Exception):
    print("Это проблема")

raise MyError("ошибка MyError")
Traceback (most recent call last):
  File “”, line 1, in 
    raise MyError(“ошибка MyError”)
MyError: ошибка MyError

Вот и все, что касается обработки исключений в Python.

8. Вывод: обработка исключений Python

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

We have explored basic python till now from Set 1 to 4 (Set 1 | Set 2 | Set 3 | Set 4). 

In this article, we will discuss how to handle exceptions in Python using try. except, and finally statement with the help of proper examples. 

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. 

Difference between Syntax Error and Exceptions

Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the termination of the program. 

Example: 

Python3

amount = 10000

if(amount > 2999)

print("You are eligible to purchase Dsa Self Paced")

Output:

Exceptions: Exceptions are raised when the program is syntactically correct, but the code resulted in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program.

Example:

Python3

marks = 10000

a = marks / 0

print(a)

Output:

In the above example raised the ZeroDivisionError as we are trying to divide a number by 0.

Note: Exception is the base class for all the exceptions in Python. You can check the exception hierarchy here.  

Try and Except Statement – Catching Exceptions

Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

Example: Let us try to access the array element whose index is out of bound and handle the corresponding exception.

Python3

a = [1, 2, 3]

try

    print ("Second element = %d" %(a[1]))

    print ("Fourth element = %d" %(a[3]))

except:

    print ("An error occurred")

Output

Second element = 2
An error occurred

In the above example, the statements that can cause the error are placed inside the try statement (second print statement in our case). The second print statement tries to access the fourth element of the list which is not there and this throws an exception. This exception is then caught by the except statement.

Catching Specific Exception

A try statement can have more than one except clause, to specify handlers for different exceptions. Please note that at most one handler will be executed. For example, we can add IndexError in the above code. The general syntax for adding specific exceptions are – 

try:
    # statement(s)
except IndexError:
    # statement(s)
except ValueError:
    # statement(s)

Example: Catching specific exception in Python

Python3

def fun(a):

    if a < 4:

        b = a/(a-3)

    print("Value of b = ", b)

try:

    fun(3)

    fun(5)

except ZeroDivisionError:

    print("ZeroDivisionError Occurred and Handled")

except NameError:

    print("NameError Occurred and Handled")

Output

ZeroDivisionError Occurred and Handled

If you comment on the line fun(3), the output will be 

NameError Occurred and Handled

The output above is so because as soon as python tries to access the value of b, NameError occurs. 

Try with 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.

Example: Try with else clause

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 exception.

Syntax:

try:
    # Some Code.... 

except:
    # optional block
    # Handling of exception (if required)

else:
    # execute if no exception

finally:
    # Some code .....(always executed)

Example:

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

Raising Exception

The raise statement allows the programmer to force a specific exception to occur. The sole argument in raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception).

Python3

try

    raise NameError("Hi there"

except NameError:

    print ("An exception")

    raise 

The output of the above code will simply line printed as “An exception” but a Runtime error will also occur in the last due to the raise statement in the last line. So, the output on your command line will look like 

Traceback (most recent call last):
  File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in <module>
    raise NameError("Hi there")  # Raise Error
NameError: Hi there

This article is contributed by Nikhil Kumar Singh(nickzuck_007) 

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

Exceptions

So far we have made programs that ask the user to enter a string, and
we also know how to convert that to an integer.

text = input("Enter something: ")
number = int(text)
print("Your number doubled:", number*2)

That works.

Enter a number: 3
Your number doubled: 6

But that doesn’t work if the user does not enter a number.

Enter a number: lol
Traceback (most recent call last):
  File "/some/place/file.py", line 2, in <module>
    number = int(text)
ValueError: invalid literal for int() with base 10: 'lol'

So how can we fix that?

What are exceptions?

In the previous example we got a ValueError. ValueError is an
exception. In other words, ValueError is an error that can occur
in our program. If an exception occurs, the program will stop and we
get an error message. The interactive prompt will display an error
message and keep going.

>>> int('lol')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'lol'
>>>

Exceptions are classes.

>>> ValueError
<class 'ValueError'>
>>>

We can also create exceptions. We won’t get an error message by doing
that, but we’ll use this for displaying our own error messages later.

>>> the_problem = ValueError('oh no')
>>> the_problem
ValueError('oh no',)
>>>

Catching exceptions

If we need to try to do something and see if we get an exception, we
can use try and except. This is also known as catching the
exception.

>>> try:
...     print(int('lol'))
... except ValueError:
...     print("Oops!")
...
Oops!
>>>

The except part doesn’t run if the try part succeeds.

>>> try:
...     print("Hello World!")
... except ValueError:
...     print("What the heck? Printing failed!")
...
Hello World!
>>>

ValueError is raised when something gets an invalid value, but the
value’s type is correct. In this case, int can take a string as an
argument, but the string needs to contain a number, not lol. If
the type is wrong, we will get a TypeError instead.

>>> 123 + 'hello'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>

Exceptions always interrupt the code even if we catch them. Here the
print never runs because it’s after the error but inside the try
block. Everything after the try block runs normally.

>>> try:
...     123 + 'hello'
...     print("This doesn't get printed.")
... except TypeError:
...     print("Oops!")
...
Oops!
>>>

Does an except ValueError also catch TypeErrors?

>>> try:
...     print(123 + 'hello')
... except ValueError:
...     print("Oops!")
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>

No, it doesn’t. But maybe we could except for both ValueError and
TypeError?

>>> try:
...     int('lol')
... except ValueError:
...     print('wrong value')
... except TypeError:
...     print('wrong type')
...
wrong value
>>> try:
...     123 + 'hello'
... except ValueError:
...     print('wrong value')
... except TypeError:
...     print('wrong type')
...
wrong type
>>>

Seems to be working.

We can also also catch multiple exceptions by catching
a tuple of exceptions:

>>> try:
...     123 + 'hello'
... except (ValueError, TypeError):
...     print('wrong value or type')
...
wrong value or type
>>> try:
...     int('lol')
... except (ValueError, TypeError):
...     print('wrong value or type')
...
wrong value or type
>>>

Catching Exception will catch all errors. We’ll learn more about why
it does that in a moment.

>>> try:
...     123 + 'hello'
... except Exception:
...     print("Oops!")
...
Oops!
>>> try:
...     int('lol')
... except Exception:
...     print("Oops!")
...
Oops!
>>>

It’s also possible to catch an exception and store it in a variable.
Here we are catching an exception that Python created and storing it in
our_error.

>>> try:
...     123 + 'hello'
... except TypeError as e:
...     our_error = e
...
>>> our_error
TypeError("unsupported operand type(s) for +: 'int' and 'str'",)
>>> type(our_error)
<class 'TypeError'>
>>>

When should we catch exceptions?

Do not do things like this:

try:
    # many lines of code
except Exception:
    print("Oops! Something went wrong.")

There’s many things that can go wrong in the try block. If something
goes wrong all we have is an oops message that doesn’t tell us which
line caused the problem. This makes fixing the program really annoying.
If we want to catch exceptions we need to be specific about what exactly
we want to catch and where instead of catching everything we can in the
whole program.

There’s nothing wrong with doing things like this:

try:
    with open('some file', 'r') as f:
        content = f.read()
except OSError:     # we can't read the file but we can work without it
    content = some_default_content

Usually catching errors that the user has caused is also a good idea:

import sys

text = input("Enter a number: ")
try:
    number = int(text)
except ValueError:
    print(f"'{text}' is not a number.", file=sys.stderr)
    sys.exit(1)
print(f"Your number doubled is {(number * 2)}.")

Raising exceptions

Now we know how to create exceptions and how to handle errors that
Python creates. But we can also create error messages manually. This
is known as raising an exception and throwing an exception.

Raising an exception is easy. All we need to do is to type raise
and then an exception we want to raise:

>>> raise ValueError("lol is not a number")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: lol is not a number
>>>

Of course, we can also raise an exception from a variable.

>>> oops = ValueError("lol is not a number")
>>> raise oops
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: lol is not a number
>>>

If we define a function that raises an
exception and call it we’ll notice that the error message also
says which functions we ran to get to that error.

>>> def oops():
...     raise ValueError("oh no!")
...
>>> def do_the_oops():
...     oops()
...
>>> do_the_oops()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in do_the_oops
  File "<stdin>", line 2, in oops
ValueError: oh no!
>>>

If our code was in a file we would also see the line of code
that raised the error.

When should we raise exceptions?

Back in the module chapter we learned to display error
messages by printing to sys.stderr and then calling sys.exit(1), so
when should we use that and when should we raise an exception?

Exceptions are meant for programmers, so if we are writing something
that other people will import we should use exceptions. If our program
is working like it should be and the user has done something wrong,
it’s usually better to use sys.stderr and sys.exit.

Exception hierarchy

Exceptions are organized like this. I made this tree with this
program on Python 3.7. You may
have more or less exceptions than I have if your Python is newer or
older than mine, but they should be mostly similar.

Exception
├── ArithmeticError
│   ├── FloatingPointError
│   ├── OverflowError
│   └── ZeroDivisionError
├── AssertionError
├── AttributeError
├── BufferError
├── EOFError
├── ImportError
│   └── ModuleNotFoundError
├── LookupError
│   ├── IndexError
│   └── KeyError
├── MemoryError
├── NameError
│   └── UnboundLocalError
├── OSError
│   ├── BlockingIOError
│   ├── ChildProcessError
│   ├── ConnectionError
│   │   ├── BrokenPipeError
│   │   ├── ConnectionAbortedError
│   │   ├── ConnectionRefusedError
│   │   └── ConnectionResetError
│   ├── FileExistsError
│   ├── FileNotFoundError
│   ├── InterruptedError
│   ├── IsADirectoryError
│   ├── NotADirectoryError
│   ├── PermissionError
│   ├── ProcessLookupError
│   └── TimeoutError
├── ReferenceError
├── RuntimeError
│   ├── NotImplementedError
│   └── RecursionError
├── StopAsyncIteration
├── StopIteration
├── SyntaxError
│   └── IndentationError
│       └── TabError
├── SystemError
├── TypeError
├── ValueError
│   └── UnicodeError
│       ├── UnicodeDecodeError
│       ├── UnicodeEncodeError
│       └── UnicodeTranslateError
└── Warning
    ├── BytesWarning
    ├── DeprecationWarning
    ├── FutureWarning
    ├── ImportWarning
    ├── PendingDeprecationWarning
    ├── ResourceWarning
    ├── RuntimeWarning
    ├── SyntaxWarning
    ├── UnicodeWarning
    └── UserWarning

Catching an exception also catches everything that’s under it in this
tree. For example, catching OSError catches errors that we typically
get when processing files, and catching Exception catches
all of these errors. You don’t need to remember this tree, running
help('builtins') should display a larger tree that this is a part of.

There are also a few exceptions that are not in this tree like
SystemExit and KeyboardInterrupt, but most of the time we shouldn’t
catch them. Catching Exception doesn’t catch them either.

Summary

  • Exceptions are classes and they can be used just like all other classes.
  • ValueError and TypeError are some of the most commonly used exceptions.
  • The try and except keywords can be used for attempting to do
    something and then doing something else if we get an error. This is
    known as catching exceptions.
  • It’s possible to raise exceptions with the raise keyword. This
    is also known as throwing exceptions.
  • Raise exceptions if they are meant to be displayed for programmers and
    use sys.stderr and sys.exit otherwise.

Examples

Keep asking a number from the user until it’s entered correctly.

while True:
    try:
        number = int(input("Enter a number: "))
        break
    except ValueError:
        print("That's not a valid number! Try again.")

print("Your number doubled is:", number * 2)

This program allows the user to customize the message it prints by
modifying a file the greeting is stored in, and it can create the
file for the user if it doesn’t exist already. This example also uses
things from the file chapter, the function defining
chapter and the module chapter.

# These are here so you can change them to customize the program
# easily.
default_greeting = "Hello World!"
filename = "greeting.txt"


import sys

def askyesno(question):
    while True:
        answer = input(question + ' (y or n) ')
        if answer == 'Y' or answer == 'y':
            return True
        if answer == 'N' or answer == 'n':
            return False

def greet():
    with open(filename, 'r') as f:
        for line in f:
            print(line.rstrip('n'))

try:
    greet()
except OSError:
    print(f"Cannot read '{filename}'!", file=sys.stderr)
    if askyesno("Would you like to create a default greeting file?"):
        with open(filename, 'w') as f:
            print(default_greeting, file=f)
        greet()

If you have trouble with this tutorial, please
tell me about it and I’ll make this tutorial better,
or ask for help online.
If you like this tutorial, please give it a
star.

You may use this tutorial freely at your own risk. See
LICENSE.

Previous | Next |
List of contents

Понравилась статья? Поделить с друзьями:
  • Raise error vba
  • Raise error rails
  • Raise error powershell
  • Raise error postgres
  • Raise error file does not start with riff id