While programming, we have to deal with many constraints which are imposed on variables so that program can be executed in proper way. To enforce the constraints on the variables, we use if else block as well as try catch blocks. In this article we will see how both the constructs work and we will look into the conditions where if-else blocks can be used and where try-except blocks can be used.
Working of if-else
If-else blocks are used in python or any other programming language to control the execution of statements in a program based on a conditional statement.If The condition mentioned in the if block is True then the statements written in if block are executed. If the condition evaluates to False, the statements written in else block of the program are executed.
If-else block is mainly used for flow control of the program based on the conditions which are known in advance to us.
For Example, suppose we are performing a division operation in our program. In this case the variable in the divisor cannot be zero. If the divisor becomes zero, the program will run into error and ZeroDivisionError
will occur.
def dividewithoutcondition(dividend,divisor):
print("Dividend is:",end=" ")
print(dividend)
print("Divisor is:",end=" ")
print(divisor)
quotient=dividend/divisor
print("Quotient is:",end=" ")
print(quotient)
#Execute the function
dividewithoutcondition(10,2)
dividewithoutcondition(10,0)
Output:
Dividend is: 10
Divisor is: 2
Quotient is: 5.0
Dividend is: 10
Divisor is: 0
Traceback (most recent call last):
File "<ipython-input-2-f6b48848354a>", line 1, in <module>
runfile('/home/aditya1117/untitled0.py', wdir='/home/aditya1117')
File "/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/aditya1117/untitled0.py", line 22, in <module>
dividewithoutcondition(10,0)
File "/home/aditya1117/untitled0.py", line 6, in dividewithoutcondition
quotient=dividend/divisor
ZeroDivisionError: division by zero
In the above implementation, we can see that when 0 is given as divisor, error occurs and program ends abruptly. To avoid the error so that program executes as desired, we can use if- else block in the following way.
def dividewithifelse(dividend,divisor):
print("Dividend is:",end=" ")
print(dividend)
print("Divisor is:",end=" ")
print(divisor)
if divisor==0:
print("Divisor cannot be Zero")
else:
quotient=dividend/divisor
print("Quotient is:",end=" ")
print(quotient)
#Execute the function
dividewithifelse(10,2)
dividewithifelse(10,0)
Output:
Dividend is: 10
Divisor is: 2
Quotient is: 5.0
Dividend is: 10
Divisor is: 0
Divisor cannot be Zero
In the above program, we have first checked for the divisor to be zero. The program works normally in the first case, i.e. when the divisor is non zero. In the second division, when divisor is zero, the program prints that divisor cannot be zero and exits normally unlike the program without any conditional check, which ran into error. So, if else blocks can be used to implement preemptive checks in a program so that the program does not run into error.
Working of try-catch
Python try-catch blocks are mainly used for error or exception handling in python. Whenever an error occurs while executing statements in the try block and exception is raised, catch block handles the exception. The statements in the try block execute normally until an error occurs. As soon as error occurs, the control goes to the catch block and the error is handled there. Generally if we don’t know which error or exception can occur while execution of the program, we use try-except block.
If we want to implement the same program to divide the numbers using try-catch block to implement the constraint that divisor cannot be zero, we can do it as follows.Here In python try-catch block is termed as try-except block.
def dividewithtryexcept(dividend,divisor):
print("Dividend is:",end=" ")
print(dividend)
print("Divisor is:",end=" ")
print(divisor)
try:
quotient=dividend/divisor
print("Quotient is:",end=" ")
print(quotient)
except(ZeroDivisionError):
print("Divisor cannot be Zero")
Output:
Dividend is: 10
Divisor is: 2
Quotient is: 5.0
Dividend is: 10
Divisor is: 0
Divisor cannot be Zero
Here, the output produced is exactly same as the output when the function was implemented using if-else block. But the working of the two constructs are entirely different. The if-else block works preemptively and stops the error from occurring while the try-except block handles the error after it has occurred. So, In try-except block system usage is more than if-else block.
Benefits of try-catch over if-else
- Try-catch block can be used to handle system generated errors as well as to implement conditional statements by manually raising exceptions while if else block can only implement conditional statements and cannot handle system generated errors.
- A single try block can check as many conditions as we want and then throw errors which will be handled by the catch block. Whereas we have to implement a if block explicitly for each condition while using if-else block.
- If else blocks bring a lot of complexity in source code but try except blocks are straightforward and hence using try-catch block ensures that readability of source code is maintained.
Benefits of if-else over try-catch
- If else statements act in a preemptive way and prevent the error from occurring by checking the conditions while try-catch blocks allow the error to occur due to which control goes back to the system and then the system transfers the control back to the catch block. In this way, if else blocks are more efficient than try-catch statements.
- If-else blocks are handled entirely by the application program but when an exception is raised from the try block when using try-catch,the control is transferred to the system and then again the system transfers the control back to the application program and the exception is handled by the catch block. Due to this reason, try-except blocks are more costly than if-else blocks in execution.
When to use if-else block?
If-else blocks must be used instead of try-catch blocks when the programmer knows in advance about the conditions which may arise while execution of the program. Using if else statements instead of try-except blocks in such cases will make the program more efficient.
When to use try-catch?
There may be many situations where the programmer may not be able to predict and check all the conditions. This may lead to error in the program execution. In such cases, to handle the untackled errors, the programmer should use try-except block instead of if-else statements.
Whenever performing file operations like python read file or writing to file, it may happen that file is not present in the file system or an error occurs before closing the file when writing to files. If it happens, program may run into error and work done before that can be lost. To avoid these things try-except block must be used while performing file operations.
Conclusion
Keeping in mind the above points, it can be concluded that if we are writing a source code in which we already know each constraint and the values which can be taken by the variables, if-else statements should be used to implement the constraints. When we do not know what situations will be encountered during execution of the program, we should use try-except or try-catch block. Also we should try to avoid using try-catch or try-except blocks for flow control. Only if-else blocks should be used for flow control. Also, while performing file handling operations, we must use try-except block. Stay tuned for more informative articles.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.