What is an Exception?
An exception in Python is an incident that happens while executing a program that causes the regular course of the program's commands to be disrupted. When a Python code comes across a condition it can't handle, it raises an exception. An object in Python that describes an error is called an exception.
When a Python code throws an exception, it has two options: handle the exception immediately or stop and quit.
Exceptions VS Syntax Errors
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the termination of the program.When the interpreter identifies a statement that has an error, syntax errors occur.
Exceptions: Exceptions are raised when the program is syntactically correct, but the code resulted in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program. When syntactically valid Python code produces an error, this is the kind of error that arises is called Exception.
Try and Except Statement - Catching Exceptions
In we catch exceptions and handle them using try and except code blocks. The try clause contains the code that can raise an exception, while the except clause contains the code lines that handle the exception.
l=["red","green","blue"]
try:
print(l[4])
except:
print("Invalid Index")
Comments
Post a Comment