Python Tutorial
What is Exception and Exception Handling in Python
What is Exception Handling in Python?
Syntax errors and exceptions are the two forms of mistakes in Python. Errors are issues in a program that causes the program to halt its execution. Alternatively, exceptions are raised when internal events occur that disrupt the program's usual flow.
Syntax Error in Python
As the name implies, this mistake is produced by incorrect code syntax. The program is terminated as a result of this.
Example:
amount = 1000
if(amount > 299)
print("You are eligible to buy Dsa Self Paced")
Output:
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.8/py_compile.py", line 150, in compile
raise py_exc
py_compile.PyCompileError: File "./prog.py", line 2
if(amount > 299)
^
SyntaxError: invalid syntax
What are Exceptions in Python?
When a program is syntactically accurate yet the code produces an error, an exception is thrown. This error does not stop the program from running, but it does disrupt the typical flow of the program.
Example:
# initialize the amount variable
marks = 100
# perform division with 0
a = marks / 0
print(a)
Output.
Traceback (most recent call last):
File “/home/f3ad05420ab851d4bd106ffb04229907.py”, line 4, in
a=marks/0
ZeroDivisionError: division by zero