We can learn about types of errors.
Error: Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the programs.
There are two types of Error:
- Syntax Error: This type of error occurs when there is something wrong in the syntax of a code.
For example:
This type of error can be solved by checking the syntax of the code.
2. Logical Error: This type of error occurs when everything is right in the syntax of the code, still the code throw error.When in the runtime an error that occurs after passing the syntax test is called exception or logical type. For example, when we divide any number by zero then the ZeroDivisionError exception is raised, or when we import a module that does not exist then ImportError is raised.
If we see the above error it is not a syntax error. We got the error like ZeroDivisionError: division by zero.
Now we will raise the exception, we can modify the error.
We can see that the above code threw an Exception not an error.
An exception is an event, which occurs during the execution of the program, that disrupts the normal flow of the program’s instructions. The process of responding to the occurrence, during computation, of exceptional conditions requiring special processing — often changing the normal flow of the program execution.
We can learn about built-in exceptions in this link
Now we will handle the error with python methods, let’s understand the methods one by one.
- try: This is the keyword that keeps the segment of code under check.
- except: segment to handle the exception or error and correct it.
- else: this will be executed if there is no exception
- finally: this will run irrespective of anything
It is starting with a try, a code to be executed and we are expecting an error so excepting the correct error and defining the error with an exception and we can determine how our program will respond.
we have kept multiple exceptions with one correct logic and another with incorrect logic.
3. Else Clause
In the above code, we can find else clause which is reading the file and gives us the appropriate error message.
4. Finally Clause: It will run in every case
In the above code, we are using the finally clause, which executes every time without encountering previous exceptions.
Thank you, please feel free to suggest improvements
Connect over LinkedIn.
References: