Updated June 12, 2023
Definition of Python 3 Exception
Python 3 exception, when our program detects an error, Python raises a number of built-in exceptions. The program will crash if it is not handled properly. Python has two very useful methods for handling unexpected errors and adding debugging capabilities to our Python programs. Errors are a type of unchecked exception that are irrecoverable, such as an out-of-memory, which a program should avoid handling. When a Python script throws an exception, the exception object is produced. The program will be forced to end abruptly if the script does not explicitly handle the exception.
What is Python 3 exception?
- Error handling improves the resilience of our code, protecting it from any faults that could cause our application to exit unexpectedly.
- We cannot handle errors in python, but we can handle the Python exceptions. We can say the error is a syntactic (parsing) problem, however, there are many different kinds of exceptions that might occur during execution and aren’t always unusable.
- An Error may signal significant issues that a reasonable application should not attempt to solve.
- Exception handling strengthens our code and helps us avoid probable failures that may cause our program to crash unexpectedly. Consider what would happen if we wrote code that was deployed in production but still terminated due to an error. It’s best to handle the exception ahead of time and avoid the issue.
- Even though a statement or expression’s syntax is accurate, it may nonetheless generate an error when performed. Python exceptions are errors that are recognized during execution.
- Even though a statement or phrase is syntactically correct, attempting to execute it may result in an error. Exceptions are errors that are identified during execution and are not always fatal. Programs do not handle the majority of exceptions.
- The following is how the try statement operates. The try clause is executed first.
- The except clause is bypassed if no exception is thrown, then our try statement is completed.
- The rest of the clause is bypassed if our program causes exceptions during the try clause’s execution. The except clause is then executed if its type matches the exception stated after the except keyword.
- If an exception occurs that isn’t the one listed in the except clause, it’s sent on to the outer try statements, it’s an unhandled exception, and execution ceases with the message displayed above.
Python 3 exception Standard list
Below is the standard exception list of python is as follows.
- Exception – This is the base class of all the exceptions.
- StopIteration – This was raised when the next method is not pointing to any object.
- System.exit – This is raised by sys.exit function.
- StandardError – This was the base class of system exit and built-in exception.
- ArithmeticError – This is the base class of all errors which occurred at the time of calculating errors.
- OverflowError – This is raised when calculation will exceed the limit of numeric type.
- FloatingPointError – It is raised at the time calculation is fails.
- ZeroDivisionError – It is raised when module by zero for all types of numeric values.
- AssertionErrror – It was raised when failure of the statement of assert.
- AttributeError – It is raised when failure in case of assignment of reference.
- EOFError – This was raised at a time when there is no input from input or raw input.
- ImportError – It was raised when the import statement will fail.
- KeyboardInterrupt – This exception is raised when the user interrupts the execution of the program.
- LookupError – This is the base class of errors of lookup.
- IndexError – This was raised when the index is not found in the sequence.
- KeyError – This exception is raised when we have not found any specific key in the dictionary.
- NameError – This exception is raised when we have not found any namespace.
- UnboundLocalError – It was raised when we are trying to access the local variable from the function.
- EnvironmentError – This is the base class of all exceptions that occurred in the environment of python.
- IOError – It is raised when operation of input and output will fail.
- OSError – It was raised related to the OS error.
- SyntaxError – This error is raised when an error in python syntax.
- RuntimeError – This exception occurs when generated errors which not fall in any category.
- Below is the example of assertion error exception in python 3 is as follows.
Code:
def temp (temp1):
assert (temp1 >= 0),"Cold temp"
return ((temp1-231)*1.5)+33
print (temp(231))
print (int(temp(459.53)))
print (temp(-4))
Output:
Python 3 Exception Errors
- When a program’s syntax is valid but the code produces an error, an exception is thrown. This mistake does not prevent the application from running, but it does disrupt its normal flow.
- The try clause contains statements that can raise exceptions, while the except clause contains the exception.
- Below is the example of python 3 exception errors are as follows.
Code:
stud_mark = 70
stud = stud_mark / 0
print (stud)
Output:
- In below example, we are accessing the array element, which array is out of bound. We are handling this exception by using try except are as follows.
Code:
stud_mark = [35, 55, 45]
try:
print ("Element1 = %d" %(stud_mark[1]))
print ("Element2 = %d" %(stud_mark[3]))
except:
print ("Error occurred")
Output:
Python 3 Exception Examples
Below is the example of python 3 exceptions are as follows.
Example #1
In the below example, we are not using the correct indentation.
Code:
if (mark<35):
print ("Python")
Output:
Example #2
The below example shows specific exceptions in python 3 are as follows.
Code:
def fun (stud_mark):
if stud_mark < 40:
stud_mark1 = stud_mark/(stud_mark-30)
print("Value of stud_mark = ", stud_mark)
try:
fun(30)
fun(50)
except ZeroDivisionError:
print("Error occurred and handled exception")
except NameError:
print("Handled exception")
Output:
Example #3
Below example shows try with else clause are as follows.
Code:
def py1(st1 , st2):
try:
c = ((st1+st2) / (st1-st2))
except ZeroDivisionError:
print ("st1/st2 0 result")
else:
print (c)
py1(1.0, 4.0)
py1(3.0, 3.0)
Output:
Conclusion
Error handling improves the resilience of our code, protecting it from any faults that could cause our application to exit unexpectedly. When a Python script throws an exception, the exception object is produced. The program will be forced to end abruptly if the script does not explicitly handle the exception.
Recommended Articles
This is a guide to Python 3 Exception. Here we discuss the definition, What is python 3 exception is, Standard list, errors, and examples with code implementation. You may also look at the following articles to learn more-