When should I write else
in try-
statement?
There seems to be no difference between codes 1, 2, and 3 below
If the else
statement is executed when no error occurs in the try
statement,
Can't you just not write else
or keep writing it under the try
statement?
#1
try:
A = 3
except:
pass #handler
else:
A = 5
#2
try:
A = 3
A = 5
except :
pass #handler
#3
try:
A = 3
except
pass #handler
A = 5
According to Handling Exceptions
Writing the else
statement is better than writing additional code in the try
statement.
I'll explain it in the following cases.
#Code1 - else statements are written
try:
open("myfile.txt")
except :
print "IOError!"
else:
print "all fine!"
n = int(input())
print 1/n
#Code2 - When written in try
try:
open("myfile.txt")
n = int(input())
print 1/n
except :
print "IOError!"
else:
print "all fine!"
The programmer wrote the code with the intention of making an exception only when "myfile.txt"
was not present
However, since code 2 has print 1/n
in try
, if zeroDivisionError
occurs, this also proceeds to the exception handling step.
Therefore, it is possible to prevent accidental exception handling by putting a code that does not want exception handling in the else
statement like code 1.
© 2024 OneMinuteCode. All rights reserved.