Python Try a Dunction if Error Wait Try Again

As a Python developer you lot've probable come across an exception—whether you realized it or non. If you attempt to run a script that contains a syntax error, Python raises an exception. To go a successful developer, you'll take to learn how to handle these errors equally they arise.

In this article, we'll learn about Python's try and except keywords and how they're used to handle exceptions. We'll testify an example of exception handling clauses, learn more almost the context managing director for exceptions, and prove how to handle exceptions in an API request.

What Is an Exception?

In the Python programming linguistic communication, an exception (brusque for exceptional event) is an error detected during execution. Python raises an exception whatsoever time yous endeavor to divide by zero, admission an unresponsive database, or indent your code improperly, among other situations.

Exceptions are also objects derived from the Python core class Exception. The Exception object contains data almost the nature of the error in your code. Python provides a number of built-in exceptions, and libraries are free to extend the Exception grade to implement their own.

Exceptions in Python

We use the try and except keywords to catch, or handle, exceptions. Catching exceptions is crucial, as uncaught exceptions will cause your program to crash.

With that in mind, allow's accept a look at some common exceptions in Python.

Common Python Exceptions

Python comes with quite a few congenital-in exceptions that it raises for common error conditions. Here are the exceptions that you'll near often come across when you start working with Python:

Exception Name Description
AssertError An exception that is raised when an assertion fails. Usually used for debugging and unit of measurement testing.
KeyError An exception that is raised when Python cannot find a given central in a dictionary object.
MemoryError The Python exception that is raised when your program runs out of available memory.
ModuleNotFoundError An exception that Python raises when the specified module cannot be found in an import statement.
NameError An exception that Python raises when an undefined variable is used.
OSError A grouping of similar exceptions that are raised when your computer'due south operating arrangement has an fault.
RuntimeError A miscellaneous exception that is raised when none of the other built-in Python exceptions use.
StopIteration An exception raised when you call adjacent() on an iterator, but there are no more than objects in the list to iterate through.
SyntaxError A Python exception that is raised when there is a problem with the syntax of your code.
TabError An exception that is raised when your code has incorrect indentation.
TypeError The Python exception that is raised when an object is of the incorrect data blazon for a given performance.
ZeroDivisionError The exception that is raised when you endeavor to split up a number past nix.

For more Python exceptions, take a look at Python's exception documentation. Note that each library implements its own exceptions, and then you lot'll likely come across exceptions other than those found in the Python transmission.

Next, permit's generate an uncaught exception and see how Python deals with it.

Uncaught Exception Example

Before nosotros begin treatment errors with endeavour and except, let'due south look at what happens when your code causes an uncaught exception. As an instance, permit's consider what would happen if you were to divide an integer by zero. Nosotros'll run this lawmaking:

respond = 50 / 0 print(answer)            

In mathematics, any number divided by naught results in an undefined result. In Python, this is what nosotros become:

Call back that upon reaching an exception, Python stops executing the plan on the line where information technology occurred. Execution never reaches the print argument, and our program crashes instead.

Now let's look at how we tin can catch the exception and handle it.

Handling Exceptions With Python'south Try and Except Keywords

Nosotros know that uncaught errors cause our programme to crash, so the next pace is learning how to catch and handle exceptions. We'll be using the Python keywords try and except to create blocks of code that can grab exceptions.

A try block, or clause, contains the functions and code that could raise an exception. An except clause contains the logic for handling the exception. Let's build on our earlier lawmaking snippet and add try and except.

In this instance, we'll first define the respond variable, and and then attempt to use information technology to store the result of a divide by zero operation. At the cease, we'll print the respond and meet if information technology's None or if it contains a result. Allow's have a expect at the code:

answer = None   effort:   respond = 50 / 0 except ZeroDivisionError:   print("[!] Exception defenseless")   print(reply)            

This fourth dimension we wrapped our ill-fated division operation in a try clause. Our except clause contains a print argument to allow u.s. know that information technology caught an exception. Finally, we print the answer. Here's the output we get from running our code:

As yous tin see, the exception was caught in the attempt block, the reply variable remained untouched, and the program didn't crash. To bulldoze the point abode, let's try the same code again, this time dividing past two instead of null:

answer = None   endeavor:   answer = fifty / 2 except:   impress("[!] Exception defenseless")   print(answer)            

We'll run the code and look at the output:

This fourth dimension the lawmaking in our except block never ran, so we know in that location was no exception. We receive the expected result.

Using the Exception Context Manager

We can improve upon our previous code by trapping the exception we defenseless in the except clause and learning more about it. We do this by using an exception context director and storing the exception object in a variable. And then we're gratuitous to piece of work with the exception like any other object. Here's a snippet:

except Exception every bit err:      print(f"[!] Exception caught: {err}")            

The code above catches every error of the type Exception and passes it to the except clause in a variable named err. This lets united states of america impress err to learn more than most the exception.

Next, allow'due south take a await at Python's endeavour and except keywords in a existent-globe example using a context manager.

Exception Treatment in Python: An Example

If y'all've e'er seen a 404 message while browsing the web, you know that errors tin can occur while making HTTP requests. In Python, we accept to bargain with HTTP errors while making requests to an API server. Sometimes the server is unavailable, or your network connectedness is disrupted, and Python raises an exception.

Handling Exceptions in HTTP Requests

In this case, we'll employ Python's try and except keywords to write a office that makes an API asking. Our lawmaking will attempt to make a request from the server, and if information technology fails nosotros'll catch the exception and try again.

Permit'south start past importing the libraries we need and defining some variables. We'll need the requests library to make the HTTP request to our API server, and the time library to introduce a short filibuster betwixt API requests. Nosotros'll store the URL of the API server in our url variable, and define an empty response variable for the request.

import requests import time   url = "https://reqres.in/api/users" response = None            

With that in identify, permit's create the loop that nosotros'll use to continually make requests until we receive a response. Following our while loop, we'll wrap the asking in a endeavour statement and store the response.

while response is None:   try:      response = requests.go(url)            

If the asking fails to reach the server for any reason, we'll need to handle the exception. We'll use the except statement and create an exception context manager. If our request causes an error, we'll catch it here, print the exception, and expect five seconds before trying over again:

except requests.HTTPError every bit e:      print(f"[!] Exception caught: {e}")      fourth dimension.sleep(5)            

Once our request succeeds, nosotros'll impress the response:

Here's the exception handling lawmaking in total:

import requests import time   url = "https://reqres.in/api/users" response = None   while response is None:   try:      response = requests.get(url)   except requests.HTTPError as eastward:      print(f"[!] Exception defenseless: {e}")      time.slumber(5)   print(response.content)            

At present let's demonstrate a few exceptions and prove how the code retries the request until it succeeds. To facilitate this, we disabled our cyberspace connection and ran the code.

As expected, we see a number of exceptions printed on the screen. Later reconnecting to the internet, we meet the response generated by a successful request:

The screenshot higher up may exist unclear on your screen, so permit'southward zoom in and look at a single exception in more detail:

Python's requests library raised an HTTPSConnectionPool error. It was caused by a NewConnectionError in the underlying urllib library, and the reason for the mistake was a temporary failure in proper noun resolution. That'southward exactly what we'd wait if our computer were disconnected from the net.

Learn To Code With Udacity

At present that you lot've learned the basics of exception handling in Python, consider going back to your older projects and adding it. You'll notice that robust error handling will make your software more stable and reliable for your users.

To learn the core concepts of programming through HTML, CSS, and Python, check out Udacity's Introduction to Programming nanodegree. It'due south your kickoff pace toward a career as a computer programmer.

harrellfoure1940.blogspot.com

Source: https://www.udacity.com/blog/2021/09/getting-started-with-try-except-in-python.html

0 Response to "Python Try a Dunction if Error Wait Try Again"

ارسال یک نظر

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel