Red Security
Tutorial Exceptions in Python - Printable Version

+- Red Security (https://redsecurity.info/cc)
+-- Forum: Programming (https://redsecurity.info/cc/forumdisplay.php?fid=5)
+--- Forum: Python (https://redsecurity.info/cc/forumdisplay.php?fid=9)
+--- Thread: Tutorial Exceptions in Python (/showthread.php?tid=7961)



Exceptions in Python - Covid-19 - 06-08-2022

[Image: BFMMlbcQvml9HSqXcvNp]

Exceptions:
          Hello guys I hope you all are doing well. In this thread we are going to talk about exceptions. I will elaborate this concept with an example: Suppose you're making a form and you're asking the user his/her phone number. Instead of adding numbers, someone added a string. In such cases, the form application will crash. But, we can't show an error to a non-programmer. So instead of getting crashed, you can simply give Python any other thing to show up when an error is caused. That can be a simple message or any other function. That's called an Exception.
Exceptions prevent the entire program from crashing and freezing. For example if we want to divide a number by 0 then the program will crash. During run time the program mostly crashes because of user inputs. Now let's create a program to understand exceptions.

Code:
num = 10
num1 = 0
num//num1


Now if you run this code it will generate an error that will terminate the program and all the code below this will not run so it is causing the whole program to crash. But using try and except commands to save our program from crashing and show the user a message that how to do it correctly if he is doing something wrong. Now let’s solve the above issue.

Code:
try:
    num = 10
    num1 = 0
    print(num//num1)
except ZeroDivisionError:
    print("the divisor can not be zero")


So let’s first understand this code if the try block has any exception error the code in the except block will run. ZeroDivisionError after except is the type of error that can occur in this case. There are other exception types like:
ImportError
IndexError
NameError
TypeError
SyntaxError

And if you are not familiar what error can be in the try block so don’t mention anything after except the interpreter will look for each of the errors in that case.

Code:
try:
    some_text = "Hello World"
    Number = 12
    print(some_text // 12)
except:
    print("Type Error")


We have learned about try and except and now we will learn about the else statement within the try and except statement. The block of code with the else statement will only run when no errors occur in the try statement.

Code:
try:
    num = int(input())
    num1 = int(input())
    result = num / num1
except:
    print("Division by zero is not possible")
else:
    print("Result is: ", result)


Let’s now discuss the ‘finally’ statement which is run in both cases. Either try statement returns an error or not.

Code:
try:
    num = int(input())
    num1 = int(input())
    result = num / num1
except:
    print("Division by zero is not possible")
else:
    print("Result is: ", result)
finally:
    print("This will run in both cases")


The finally block is useful, for example, when working with files and resources: it can be used to make sure files or resources are closed or released regardless of whether an exception occurs.

Now we will discuss the most important concept with exceptions that is raising an exception. If a specific condition is met we use a raise statement for raising an exception error. For Example if you want to make a program that takes input for username and if the name is less than 4 characters it will return an exception now let’s code this..

Code:
while True:
    try:
        name = input()
        if len(name) < 4:
            raise NameError
    except NameError:
        print("Number Must be of 4 characters or more")
    else:
        print("Name set successfully")
        break

That’s it for this thread see you in the next...


"Keep Good care of your Health
Allah Hafiz and Good Bye Till the next post"