Monday, May 22, 2023

#PYTHON(DAY26)Exception

 

#PYTHON(DAY26)

Exception

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.

Exception

Exceptions versus Syntax Errors

When the interpreter identifies a statement that has an error, syntax errors occur. Consider the following scenario:

Example:

#Python code after removing the syntax error  
string = "Python Exceptions"

for s in string:
if (s != o:
print( s )

And the output is:

if (s != o:
^
SyntaxError: invalid syntax

The arrow in the output shows where the interpreter encountered a syntactic error. There was one unclosed bracket in this case. Close it and rerun the program:

#Python code after removing the syntax error  
string = "Python Exceptions"

for s in string:
if (s != o):
print( s )

And the output is:

 2 string = "Python Exceptions"
4 for s in string:
----> 5 if (s != o):
6 print( s )

NameError: name 'o' is not defined

We encountered an exception error after executing this code. When syntactically valid Python code produces an error, this is the kind of error that arises. The output’s last line specified the name of the exception error code encountered. Instead of displaying just “exception error”, Python displays information about the sort of exception error that occurred. It was a NameError in this situation. Python includes several built-in exceptions. However, Python offers the facility to construct custom exceptions.

In the next story let’s discuss about Try and Except statements.

No comments:

Post a Comment

Building Static Website(part6) HTML Lists

  Building Static Website (part6) HTML Lists Today, let us add some lists to our detailed view section by using html lists. Lists: List is a...