Exception handling in Python | Learn python


Exception handling in Python allows programmers to write code that can gracefully handle errors and exceptions that occur during program execution, rather than abruptly terminating the program.



In Python, an exception is an event that interrupts the normal flow of program execution. Exceptions can be caused by a wide range of issues such as runtime errors, syntax errors, and logical errors. To handle exceptions in Python, you use a try-except block. The try block contains the code that may raise an exception, while the except block contains the code that is executed when an exception is raised.

Here is an example of how to use a try-except block in Python:


output:-


In the aforementioned example, the try block tries to print "This is Guerilla Teck with no error" using incorrect print syntax. This is against the law and will result in an exception that reads "name "Print" is not defined." The action cannot be completed, and the unless block produces a message informing the user of this.

ValueError, TypeError, and IndexError are a few of the built-in Python exceptions that can be handled with a try-except block. By subclassing the built-in Exception class, you may also create your own unique custom exceptions.

It's important to note that you should only catch exceptions that you can handle properly. Catching all exceptions with a generic except block can hide errors and make debugging more difficult.

Try-Except-Else

In addition to the try-except block, Python also provides a try-except-else block for more fine-grained exception handling. The try-except-else block consists of a try block followed by one or more except blocks and an optional else block.

The syntax for the try-except-else block is as follows:


In the try block, you include the code that may raise an exception. If an exception of type ExceptionType is raised, the code in the corresponding except block will be executed. If no exception is raised, the code in the else block will be executed.

Here's an example of how to use the try-except-else block in Python:


output:-


In this example, in the try block we’re printing “This is Guerilla Teck with no error” with correct syntax. If we print above mentioned statement with the wrong print statement except block will be executed. If no exception is raised, the code in the else block will be executed and the result will be printed.


Try-Except-Finally

The try-except-finally block is used in Python for exception handling and cleanup actions. It is a variation of the try-except block and is used when you need to ensure that certain actions, such as closing a file or network connection, are performed regardless of whether an exception occurs or not.

The syntax for a try-except-finally block is as follows:


In the try block, you include the code that may raise an exception. If an exception is raised, the code in the corresponding except block is executed to handle the exception. Regardless of whether an exception is raised or not, the code in the finally block is executed. This block is often used to perform cleanup actions such as closing files or releasing resources.

Here's an example of using a try-except-finally block in Python:


output:-


Now an example with an error:-


output:-


In the first example we can see that syntax in try block is correct so the program didn’t go into except block but in the second example when the syntax in try block was incorrect then the program went into except block, but you can notice one thing is common. The code in finally block was executed in both cases.

This tells us that no matter what will happen, code in finally block will be executed.

The except statement using with exception variable

In Python, when handling an exception using the try-except block, you can use the except statement with an exception variable to capture the exception object that was raised. This can be useful for debugging or providing more informative error messages to the user.

The syntax for using the except statement with an exception variable is as follows:


In this syntax, ExceptionType is the type of exception that you want to handle, and exception_variable is the name of the variable that you want to use to refer to the exception object that was raised.

Here’s an example on how you can have an error but instead of terminating the program we can have the exception print as a message and still be continued with our code:-


output:-


We can see that in the try block giving the command for print the value of a variable that doesn’t exist will give an error but adding the keyword ‘Exception’ after except will catch the actual error and will provide us that error like a message through the exception variable ‘e’.

We can also give several except command according to a specific exception. For example: -


Output if we enter alphabet ‘a’ & number 0: -


Output if we enter number 5 & 0: -


Now here in the first output we have entered the alphabet ‘a’ and a number 5 and it will give us the error of ‘ValueError’ and to handle that specific exception we put the error’s name in front of a except so what it will do is that if this code will raise the error of ‘ValueError’, first except will handle that exception and will print a message specific to this error.

On the other hand,  if we enter the number 5 & 0, so it will raise the error of ‘ZeroDivisionError’ and to handle that specific exception we put the name of the exception that is ‘ZeroDivisionError’ in front of another except and that except will handle this exception if this exception ever comes up.

So, with this method, we can print a specific output for a specific exception.

Declaring Multiple Exceptions

We can also declare multiple exceptions in one singular except. Its very simple.
 
For example:-


output:-


So even if we entered the values of 5 & 0 or if we entered the value of an alphabet ‘a’ & a number 0, both will give the same output. Why? Because no matter what values we enter, both of the exception will be caught by the except with the name of both the exception name. but if an exception of another kind rises up so the program will get terminated and code further than except, will not be executed.




so that's it for today guys, follow us to learn more about Python topics.....

happy learning.....

No comments:

Post a Comment