0
Why we use exception handling ?
2 Answers
+ 5
As SUPERFLY already mentioned, exception handling prevents the program from crashing during execution. Many situations can create an exception like printing this: print(23 + '7'). This will create a TypeError. An uncontrolled termination of a program can also cause a loss of data or can corrupt the data.
Here the principle of an exception structure:
try:
(run this code where unexpected things can happen)
except:
(execute this part of the program if an exception occurs)
else:
(if there is no exception this part of the code will run)
finally:
(run this code in any case)
In general it's recommended to catch all exceptions that could appear, but I try to minimize that with a general approach:
try:
word = "spam"
print(word / 0)
except Exception as e:
print("An error occurred:")
print(e)
This gives the following message:
An error occurred:
unsupported operand type(s) for /: 'str' and 'int'
+ 2
Simple. So that the program doesn't crash.
The following lesson explains it so well:
https://www.sololearn.com/learn/CSharp/2690/?ref=app