Python 3 - Try / Except / Else / Finally

Python 3: From Scratch to Intermediate INTERMEDIATE LEVEL: Python 3 - Conditionals, Loops and Exceptions
9 minutes
Share the link to this page
Copied
  Completed
You need to have access to the item to view this lesson.
One-time Fee
$99.99
List Price:  $139.99
You save:  $40
€93.20
List Price:  €130.49
You save:  €37.28
£79.91
List Price:  £111.88
You save:  £31.96
CA$136.56
List Price:  CA$191.19
You save:  CA$54.63
A$153.05
List Price:  A$214.27
You save:  A$61.22
S$136.08
List Price:  S$190.51
You save:  S$54.43
HK$782.75
List Price:  HK$1,095.88
You save:  HK$313.13
CHF 91.21
List Price:  CHF 127.70
You save:  CHF 36.49
NOK kr1,100.23
List Price:  NOK kr1,540.37
You save:  NOK kr440.13
DKK kr695.05
List Price:  DKK kr973.10
You save:  DKK kr278.04
NZ$168.07
List Price:  NZ$235.31
You save:  NZ$67.23
د.إ367.25
List Price:  د.إ514.16
You save:  د.إ146.91
৳10,970.75
List Price:  ৳15,359.49
You save:  ৳4,388.74
₹8,335.10
List Price:  ₹11,669.48
You save:  ₹3,334.37
RM476.90
List Price:  RM667.68
You save:  RM190.78
₦130,608.93
List Price:  ₦182,857.73
You save:  ₦52,248.80
₨27,840.21
List Price:  ₨38,977.41
You save:  ₨11,137.19
฿3,694.31
List Price:  ฿5,172.18
You save:  ฿1,477.87
₺3,253.72
List Price:  ₺4,555.34
You save:  ₺1,301.61
B$515.88
List Price:  B$722.26
You save:  B$206.37
R1,886.05
List Price:  R2,640.54
You save:  R754.49
Лв182.13
List Price:  Лв254.99
You save:  Лв72.85
₩137,567.94
List Price:  ₩192,600.62
You save:  ₩55,032.68
₪380.78
List Price:  ₪533.11
You save:  ₪152.32
₱5,769.12
List Price:  ₱8,077
You save:  ₱2,307.87
¥15,680.08
List Price:  ¥21,952.74
You save:  ¥6,272.66
MX$1,724.22
List Price:  MX$2,413.98
You save:  MX$689.75
QR364.68
List Price:  QR510.56
You save:  QR145.88
P1,379.77
List Price:  P1,931.74
You save:  P551.96
KSh13,498.65
List Price:  KSh18,898.65
You save:  KSh5,400
E£4,789.68
List Price:  E£6,705.74
You save:  E£1,916.06
ብር5,693.24
List Price:  ብር7,970.76
You save:  ብር2,277.52
Kz83,560.30
List Price:  Kz116,987.77
You save:  Kz33,427.46
CLP$94,840.51
List Price:  CLP$132,780.51
You save:  CLP$37,940
CN¥724.59
List Price:  CN¥1,014.46
You save:  CN¥289.86
RD$5,873.12
List Price:  RD$8,222.61
You save:  RD$2,349.48
DA13,427.17
List Price:  DA18,798.58
You save:  DA5,371.40
FJ$225.97
List Price:  FJ$316.37
You save:  FJ$90.39
Q777.73
List Price:  Q1,088.86
You save:  Q311.12
GY$20,914.34
List Price:  GY$29,280.91
You save:  GY$8,366.57
ISK kr13,988.60
List Price:  ISK kr19,584.60
You save:  ISK kr5,596
DH1,011.63
List Price:  DH1,416.33
You save:  DH404.69
L1,776.81
List Price:  L2,487.61
You save:  L710.79
ден5,738.79
List Price:  ден8,034.54
You save:  ден2,295.74
MOP$805.67
List Price:  MOP$1,127.97
You save:  MOP$322.30
N$1,914.68
List Price:  N$2,680.63
You save:  N$765.95
C$3,678.96
List Price:  C$5,150.69
You save:  C$1,471.73
रु13,310.19
List Price:  रु18,634.81
You save:  रु5,324.61
S/372.97
List Price:  S/522.18
You save:  S/149.20
K385.04
List Price:  K539.08
You save:  K154.03
SAR375.02
List Price:  SAR525.04
You save:  SAR150.02
ZK2,631.59
List Price:  ZK3,684.33
You save:  ZK1,052.74
L463.78
List Price:  L649.31
You save:  L185.53
Kč2,343.96
List Price:  Kč3,281.64
You save:  Kč937.68
Ft36,581.40
List Price:  Ft51,215.43
You save:  Ft14,634.02
SEK kr1,089.92
List Price:  SEK kr1,525.94
You save:  SEK kr436.01
ARS$87,365.86
List Price:  ARS$122,315.70
You save:  ARS$34,949.84
Bs692.26
List Price:  Bs969.20
You save:  Bs276.93
COP$394,057.74
List Price:  COP$551,696.60
You save:  COP$157,638.86
₡50,249.28
List Price:  ₡70,351
You save:  ₡20,101.72
L2,468.18
List Price:  L3,455.56
You save:  L987.37
₲742,598.03
List Price:  ₲1,039,666.95
You save:  ₲297,068.91
$U3,834.62
List Price:  $U5,368.62
You save:  $U1,534
zł402.81
List Price:  zł563.95
You save:  zł161.14
Already have an account? Log In

Transcript

Okay, we've seen some Python exceptions and how they look like. But given the fact that an exception interrupts the normal execution of Python code, it would be more convenient for us to handle an exception when it occurs, and still Python to keep executing the rest of the code in the program. To do this, we will use the so called try except block for exception handling. Let's consider the zero division exception from the previous lecture and see how we can handle it properly. First, let's define the try and accept clauses. Under the try clause, you're going to insert the code that you think might generate an exception at a given point in the execution of your program.

Of course, this code is going to be one level of indentation away from the try statement. As with for while or if statements, you must always type in a colon after the try keyword below that statement, you must input the piece of code you want to be executed. Let's create a new file called try.py. And write the code we will use the same for loop from the previous examples. So let me create this file. Try.

Okay, this is the file Now let's open it using notepad plus plus. And let's type in some code for i in range of five, try colon, and let's say print i divided by zero. Okay, up to this point, you should have noticed a couple of things. First, the indentation the trace statement is indented one level to the right from the for statement. After try, a colon should always be inserted. Then we enter the code we want to check for exceptions.

This code will also be indented one level from the try statement, as you can see right here to tell Python that it belongs to the try block in this case, We are 100% positive we are going to get an exception, right, because we are going to divide a number by zero. Now let's move on to the second part the except clause. Below except we will specify what exception types should Python expect. As a consequence of running the code below the try clause, you should think of this whole try accept procedure, as if you were telling Python the following. Try to execute the indented code below the tried clause. If no exceptions are cure, while executing that code, then skip the except clause and move on to the rest of the program.

If an exception doesn't cure, and it is defined in the Accept statement, then execute the indented code below that except statement. So in our case, knowing that division by zero is not allowed. We are expecting the zero division exception. So let's tell Python how to handle it. So now decreasing the indentation. We have except zero division error as a tab, print, a comma division by zero is not allowed.

Sorry. Now let's save the file and run it by Thawne, D, colon backslash, and try dot p y. Okay, so let's analyze the result, Python took each element from the range generated by the range function, tried to divide it by zero, under the try clause right here, realized that this isn't possible, so it raised a zero division exception in the background. Now, because we already had that exact exception defined in the except clause, it didn't generate the same old output, but instead, it executed the code underneath the except clause, printing a customized output. By the way, notice that in the except clause, we should define a temporary user defined variable. I called it easy Which can be further embedded into your customized output right here, if you wish.

Otherwise, just print out whatever message you like. The use of this temporary variable is not mandatory, we could have very well written just accept zero division error, and the result would have been the same. On the other hand, if we wouldn't have had the zero division exception specified in the except clause, or if we would have had any other exception defined instead, Python would have given us the plain old exception message. Let's test this. Let's say that we didn't realize that the zero division exception may occur in the code under the try clause, but instead we wanted to cover any name exception, which could have been generated by the program. So we defined this type of potential exception in the except clause.

Let me write this code for this and then we will explain it. Now if we save the file and run entities, we should still get zero division error, right? So let's try this. As you can see, this time Python returned the old exception message. Because this time we didn't specify any customized message for this type of exception. Another thing I want to clarify is that if the code inside the try block does not generate any exceptions at all, then Python doesn't even look at the except clause and moves on to the rest of the lines of code.

To prove this, I'm going to change the denominator for the division operation to be one instead of zero, in order for the operation to be allowed. So let me also rewrite the except clause. Okay, so this is the code now let's save it and run it once again. First of all, notice I have also added the print the rest of the code function inside the for loop at the same level of indentation, as the try except block, just to show you that for each iteration. Python tries to Execute the AI divided by one operation, it succeeds without throwing any exceptions, skips the except block and then executes the rest of the code without even caring that except is standing right there. pretty rude shame on your Python.

Another thing to add here is that you can have multiple except clauses after a try clause. This enables you to be super cautious and handle multiple types of exceptions that can be raised during the execution of the code under try. As always, Don't believe me? Unless we test it. Let's add a couple of accept clauses to our existing code. Okay, now, you may ask me, but what if I want to catch all possible exceptions that can be generated by the code located under the try clause?

Well, you can just use the except clause alone without specifying an exception name to be expected. So let me show you. I'll use another file for this So that would be something like this. And let's bring error. So this is the way in which you can catch all possible exceptions that may be generated by the code inside the try block. This is however, not recommended, and it is not a good practice, because it will catch absolutely all programming exceptions which may occur and hide the actual root cause of the exception.

I strongly recommend you create multiple except clauses according to your needs, specifying the name of the exception each time. Finally, two more things about try except blocks. You can add to other clauses after the except clause or clauses they are called else. And finally, the code indented under an else clause is executed only if the code under the try clause raises no exceptions. So let me write this code. Okay, so that would be the code.

Let's save the file again and run it. The output is the expression Did one the result of four divided by two, and then the string under the else clause gets printed out because the division raised no exceptions. Now the code inside of finally clause is executed whether the code inside the try block raises an exception or not. So either way, the finally clause gets executed. Let's try this as well. I will replace the else clause with finally.

Okay, so this would be the code with the finally clause this time. Let's save the file. And now let's run it. This is the result. So we get the result of dividing four by two. And as I said, the code under the finally clause gets executed regardless of try generating an exception or not.

To prove this all the way. Let's also use some code that will generate an exception under the try clause. So let's replace two with zero. This time the code on the try will generate a zero division error and according to the difference In the code under the finally clause should, again be executed. So you can see that we indeed have the zero division error, but the string gets printed out anyway. Of course, it would have been nicer if we would have handled that error.

So zero division error print, let's see not allowed. And now let's run the file again. And this time we have not allowed because the except clause catches the zero division error. And now the string printed out by the code under the finally clause. That's almost all you need to know about exceptions and Exception Handling for your future programming tasks. So it's time to move on to the next lecture.

Sign Up

Share

Share with friends, get 20% off
Invite your friends to LearnDesk learning marketplace. For each purchase they make, you get 20% off (upto $10) on your next purchase.