- Computers & Software»
- Computer Science & Programming»
- Programming Languages
Why You Should Use Try and Except in Python?
The reasons why you should catch errors!
Most of you reasonably asking why do you need it? Why should I add a few more code lines just to catch errors?
Here are the 3 main reasons why you should use these methods:
- You will get a more straightforward format of the error.
- Your code will not be interrupted.
- You can overtake a very specific error in case if you need to.
Now let me explain each of the reasons.
I wrote a simple code for an example. I will use it to show the differences between using the try and except methods and not using them.
First code without the methods
x = 1 b = 2 sum = x + "Hello Alex!" print(sum) print("Last line")
Analyzing The Code Output
There are two variables - "x" and "y". Each of them contains a number (Integer). I'm going to take one of the variables and concatenate it with a string "Hello Alex". Most of you know that such action is forbidden and the debugger will throw an error because you cannot add a string to a number.
If you copy and paste this code to your local machine and execute it, there are two things you will notice:
- You will get an ugly error output.
- Your code will be interrupted. See the last line - it was never printed.
Check the output below.
First code without the methods - error output
G:\Python3\python.exe "C:/Users/reinc/PycharmProjects/test/Try Except/try_except" Traceback (most recent call last): File "C:/XXX/try_except", line 5, in <module> sum = x + "Hello Alex!" TypeError: unsupported operand type(s) for +: 'int' and 'str' Process finished with exit code 1
Lets add Try and Except to the code
The next snippet of a code will examine the process of the code while having the try and except methods.
The code with the methods
x = 1 b = 2 try: sum = x + "Hello Alex!" except Exception as e: print(e) print(sum) print("Last line")
Discussion about before and after using the methods
Please notice below that two things happened here, which are the same actions but in a better code design:
- We received a shorter and more readable error output.
- Our code was note interrupted. Did you notice that the last line was printed?
I've been using try and except many times. I can guarantee you that once you will get used to using it, your code will look more professional, it will have a better performance as it will never get interrupted.
Also notice that in that very specific example, I used a basic error code. In many cases when you will use more complicated tools such as "requests", you might face lots of different possible errors (and not only one error type), then you might be interested to get more accurate error outputs.
Imagine a situation at work - your boss is asking you to write a code that connects to a specific URL, logging in and that's it. Simple, isn't it?
In addition, your boss wants to know what was the reason for the connection error and he wants to receive this error immediately once it occurred.
Will you run that code manually? Copy and paste it, then send it to your boss manually via email?
The best practice would be to wrap the connectivity code part with try and except method and right after it to add a few more lines which will send the email with the exception right yo your boss.
Please remember, the code will not be interrupted with try and except methods.
At the end of the day, your boss will be satisfied with you completing the task, he will be delighted with receiving the exception via email and you will be happy that you completed your boss's task and provided a solution for him.
The code with the methods - error output
G:\Python3\python.exe "C:/Users/reinc/PycharmProjects/test/Try Except/try_except" unsupported operand type(s) for +: 'int' and 'str' <built-in function sum> Last line Process finished with exit code 0
My Tutorial For Beginners
My Tutorial For Advanced Level
A programmer must know how to use try and except methods. This is not only about Python, this is relevant for any type of programming language that allows the programmer to catch errors.
Last tip, if you ever used the "logging" module, you should try to combine it with the try and except methods. It's a great combination of writing a log file with specific points of failure inside of the code while it is running.
One more important thing, if you work in a big corporate with many other developers, you should remember the others will see your code, they will judge your work, this is your developer "stamp" of who and how the code was written.
This content is accurate and true to the best of the author’s knowledge and is not meant to substitute for formal and individualized advice from a qualified professional.
© 2020 Alex Ledovski