else: #this code executes if no except block is executed
考虑以下程序。
例 2
try: a = int(input("Enter a:")) b = int(input("Enter b:")) c = a/b print("a/b = %d"%c) # Using Exception with except statement. If we print(Exception) it will return exception class except Exception: print("can't divide by zero") print(Exception) else: print("Hi I am else block")
输出:
Enter a:10 Enter b:0 can't divide by zero <class 'Exception'>
无异常的异常语句
Python 提供了不在异常语句中指定异常名称的灵活性。
考虑下面的例子。
例
try: a = int(input("Enter a:")) b = int(input("Enter b:")) c = a/b; print("a/b = %d"%c) except: print("can't divide by zero") else: print("Hi I am else block")
与异常变量一起使用的 except 语句
try: a = int(input("Enter a:")) b = int(input("Enter b:")) c = a/b print("a/b = %d"%c) # Using exception object with the except statement except Exception as e: print("can't divide by zero") print(e) else: print("Hi I am else block")
输出:
Enter a:10 Enter b:0 can't divide by zero division by zero
try: #this will throw an exception if the file doesn't exist. fileptr = open("file.txt","r") except IOError: print("File not found") else: print("The file opened successfully") fileptr.close()
try: age = int(input("Enter the age:")) if(age<18): raise ValueError else: print("the age is valid") except ValueError: print("The age is not valid")
输出:
Enter the age:17 The age isnot valid
示例 2 通过消息引发异常
try: num = int(input("Enter a positive integer: ")) if(num <= 0): # we can pass the message in the raise statement raise ValueError("That is a negative number!") except ValueError as e: print(e)
输出:
Enter a positive integer: -5 That is a negative number!
例 3
try: a = int(input("Enter a:")) b = int(input("Enter b:")) if b is0: raise ArithmeticError else: print("a/b = ",a/b) except ArithmeticError: print("The value of b can't be 0")