Handling an exception
Categories: Python
If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.
Here are few important points about the above-mentioned syntax −
1. A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.
2. You can also provide a generic except clause, which handles any exception.
3. After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.
4. The else-block is a good place for code that does not need the try: block's protection.