Some exceptions may occur during program execution, which may exist. For example, when you read a file, the file does not exist. In this case, we can handle exceptions.
1. Error
Let's do a simple test. We intentionally write the print method into the print method.
>>> Print ("Hello World ")
Traceback (most recent call last ):
File "<pyshell #0>", line 1, in <module>
Print ("Hello World ")
Nameerror: Name 'print' is not defined
>>>
The system will throw a nameerror exception.
2. try... try t
We can use try... try t to handle exceptions.
try: f = open("test.txt") f.close()except(IOError): print("The file is not exist.")except: print("Some error occurred.")print("Done")
Running result:
The file is not exist.
Done
3. Exception
You can use the raise statement to raise an exception. First, we need to customize a shortinputerror exception and inherit the exception class.
class ShortInputError(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleasttry: s = input("Enter something -->") if len(s) < 3: raise(ShortInputError(len(s), 3)) #Other work can continue as usual hereexcept(EOFError): print("Why did you do an EOF on me?")except ShortInputError as e: print("ShortInputError: The input was of length %d, \was expecting at least %d" % (e.length, e.atleast))else: print("No exception was raised.")
Enter two characters to run the result:
>>>
Enter something --> tr
Shortinputerror: the input was of length 2, was expecting at least 3
>>>
Enter three or more characters to run the result:
>>>
Enter something --> Test
No exception was raised.
>>>
4. Try... finally
What should you do if you want to close the file regardless of whether an exception occurs? This can be done using finally blocks. Note: In a try block, you can use the limit t clause and the Finally block. If you want to use them at the same time, you need to embed one into another.
import timetry: f = open("poem.txt") while True: # our usual file-reading idiom line = f.readline() if len(line) == 0: break time.sleep(2) print(line),finally: f.close() print("Cleaning up...closed the file")
Running result:
>>>
Programming is fun
When the work is done
If you wanna make your work also fun:
Use python!
Cleaning up... closed the file
>>>
def divide(x, y): try: result = x/ y except ZeroDivisionError: print("Division by zero!") else: print("result is", result) finally: print("executing finally clause")
Test results:
>>> Divide (2, 1)
Result is 2.0
Executing finally Clause
>>> Divide (2, 0)
Division by zero!
Executing finally Clause
>>> Divide ("2", "1 ")
Executing finally Clause
Traceback (most recent call last ):
File "<pyshell #13>", line 1, in <module>
Divide ("2", "1 ")
File "<pyshell #10>", line 3, in divide
Result = x/y
Typeerror: Unsupported operand type (s) for/: 'str' and 'str'
>>>