Introduction
During the execution of a program, an exception occurs, which interrupts the normal flow of instructions. Python scripts must handle exceptions immediately, or they terminate and quit when an exception occurs. Exceptions are Python objects that represent errors.
An error in Python can be either a syntax error or an exception. This article explains what Exception Handling is.
Also See, Floor Division in Python, Swapcase in Python
What is an Exception?
The programmer can handle an exception if it occurs at runtime. Python represents exceptions as classes.
Errors can be categorized into three types:
- Compile-time error: Software can contain errors such as missing semicolons, incorrectly spelled keywords, or errors in syntax. These errors are called syntactical errors or compile-time errors.
- Logical Error: A problem with a program that causes it to run inaccurately without causing the program to terminate abnormally.
- Runtime Error: A runtime error happens when a program you're using or writing crashes or produces a wrong output. The program may not be able to function correctly.
In other words, as a developer, you need to address all these errors and prevent what a user can do wrong to cause the application to crash. The user is not only responsible for these errors but also the server, internet connection, database connection, etc. Exception Handling in Python means that the execution should not be halted even if you encounter an error or Exception.
Also See, leap year program in python
Recommended Topic, python packages
For example:
x=8
y=0
print(x/y)
print(“end”)
Output:
In this program, we can see that x/y = 8/0 gives ZeroDivisionError, but this won't be easy to understand by a normal user.
Another problem with your execution is that you stopped it in between, so the "end" didn't appear on the screen.
To solve this problem we can use a try-except block like below:
x=8
y=0
try: //try block
print(x/y)
except Exception: //except block
print("Given number cannot be divided by Zero") //Write the message for the user
print("end")
Output:
A try-except block allows you to avoid the termination of the code in between, and it also clarifies what the exact error is to the user.
Types of Exceptions
There are two types of Exceptions:
-
Built-in Exception:
All built-in BaseException classes are based on this class already present in Python.
-
User-Defined Exception: An Exception created by a programmer is known as a user-defined exception.
Also see, Fibonacci Series in Python and Convert String to List Python.