Python Try Except Try Again in 1 Sec

Photo by Quangpraha on Pixabay

Practice Non Corruption Endeavour Except In Python

Like most other programming languages, Python supports catching and handling exceptions during runtime. However, sometimes I institute that it has been overused.

Information technology turns out that some developers, especially those who are newbies in Python, tend to utilize try … except … a lot, once they found such a feature. However, I would say that we should endeavor to avoid using that if possible, especially during the early stage of development. You volition notice that it is amend to permit the trouble reveal, rather than hide information technology.

In this article, I volition demonstrate some examples to show how "endeavour … except …" can create problems and what is the amend manner in Python programming.

Photo by geralt on Pixabay

Allow's get-go with a problematic example, which is a very typical scenario that I have seen.

          def f1(num):
endeavour:
return (num+1)*2
except Exception as e:
print('Error: ', e)
def f2(num):
attempt:
return (num+1)*three
except Exception every bit e:
print('Fault: ', e)
def f3(num):
try:
return (num+1)*4
except Exception every bit e:
print('Mistake: ', due east)

We have three functions that do some elementary numerical calculations. All of them are implemented with effort … except … with everything. And so, we desire to apply them in our code equally follows.

          num1 = f1(5)
num2 = f2('5')
num3 = f3(5)

Delight note that I deliberately laissez passer a string "5" in the second function, because I just desire to create an exception artificially. The result we accept is as follows.

Well, here we accept only a few lines of code. Information technology is non also difficult to realise the problem, perhaps. Nevertheless, imagine that you lot are doing a project that has a much larger scale, the error message must be str, not int will not be very helpful for yous to locate the trouble.

Photo past guvo59 on Pixabay

The mistake message we tin can get from the exception object east is sometimes very limited. I would say that it does not always make sense in Python. In fact, the previous one is not likewise bad because at to the lowest degree it tells y'all why the error happened. Let's encounter this one.

          def f4(key):
try:
d = {'a': ane, 'b': 2}
return d[key]
except Exception as e:
print('Error: ', e)
f4('c')

Of course, in this example nosotros have just one line of code, we know what is the "c". However, once more, if this happens in a project, how could we troubleshoot the problem if we were just given an mistake bulletin "c"?

Photograph by Ramdlon on Pixabay

Can you lot imagine that the case tin can be worse? Well, this one might not be 100% related to our topic, just I simply want to nowadays it because information technology tin can be potentially solved by the solutions in the afterward section.

Do y'all recollect it gonna be very safe if we put all of the code in the try block and catch all the generic exceptions in the except block? The answer is no. Otherwise, I volition probably recommend using it everywhere :)

Allow's encounter this case.

          def f5(num):
effort:
render num*iii
except Exception equally e:
impress('Error: ', e)
num = f5('5')
impress('Result is', num)

Again, we define a very simple numerical computing function and pass a cord into it. We might expect that the "exception" will be defenseless, but there is no exception.

Python is besides flexible to accept an mistake :)

Photo by geralt on Pixabay

If you desire to endeavor all your lawmaking and catch the exceptions, you can employ the traceback library which is born Python. Permit's use the aforementioned examples as above shown.

          import traceback          def f4(central):
try:
d = {'a': 1, 'b': ii}
return d[primal]
except Exception as e:
eastward = traceback.format_exc()
print('Mistake: ', due east)
f4('c')

Using traceback helped us to print more data about the error, so it volition be easier for united states of america to troubleshoot the problem. All the same, we need to import an extra library and write more code to do this.

Just demand to think twice nigh whether it is worth doing this? Let'southward see another good manners.

Photo by lechenie-narkomanii on Pixabay

This department is added just in example someone will say something like:

why utilize raise or assert? The full traceback stack will exist only displayed if you lot don't use try … except … at all!

Indeed, this is what I want to say in this article. It is exactly the solution to the title "Do not abuse try … except … in Python". The reason that I provide the ii "solutions" below is simply want to demonstrate what is the skillful way.

Photo by Pezibear on Pixabay

As I said earlier, we should avoid using likewise much endeavour … except … which can hide the exceptions. In contrast, we would like to have the exception reveal as much every bit possible. Using heighten to manually enhance an exception is ane of a good manner.

Allow's modify our f1, f2 and f3 functions.

          INVALID_NUM_EXCEPTION = Exception('The parameter must be integer!')          def f1(num):
if blazon(num) != int:
enhance INVALID_NUM_EXCEPTION
return (num+1)*two
def f2(num):
if type(num) != int:
raise INVALID_NUM_EXCEPTION
return (num+1)*2
def f3(num):
if type(num) != int:
raise INVALID_NUM_EXCEPTION
return (num+1)*two

Here, we defined an exception and raise it in the functions when the type of arguments passed in are not an integer.

Then, let's run the same code to use these functions.

          num1 = f1(5)
num2 = f2('5')
num3 = f3(5)

It is not too bad to come across an error if it tells yous what is the mistake exactly and where did that happen.

Photo by aitoff on Pixabay

Although exclamation is more often used in testing, we tin still use it during development to make sure that our code has fewer bugs. Also, it is usually kind of neat to use exclamation than raising an exception, if we don't care what'south the exact exception type.

          INVALID_NUM_MSG = 'The parameter must exist integer!'          def f1(num):
affirm isinstance(num, int), INVALID_NUM_MSG
return (num+1)*2
def f2(num):
assert isinstance(num, int), INVALID_NUM_MSG
return (num+1)*ii
def f3(num):
affirm isinstance(num, int), INVALID_NUM_MSG
return (num+one)*2

Photo by pasja1000 on Pixabay

It is skilful to know more tricks in a programming language. I have to say that whenever I know something absurd, I would also tend to use information technology. Nevertheless, information technology likewise needs to retrieve twice whether nosotros need to do this and if that pull a fast one on gives usa more than benefit than barriers.

Therefore, do not put all your code in the try … except … block in Python. Allow the error reveal and brand our life easier!

If y'all feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)

mizellthereaven.blogspot.com

Source: https://towardsdatascience.com/do-not-abuse-try-except-in-python-d9b8ee59e23b

0 Response to "Python Try Except Try Again in 1 Sec"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel