Nearby lessons
81 of 159Python - Default Except Block
- Understand what the default except block does and when it runs
- Write a default except block using the bare except: syntax
- Apply the rule that the default except block must always be the last block
- Explain why placing the default except block first raises a SyntaxError
Default except Block
We can use the default except block to handle any type of exception.
The default except block does not specify any exception type.
Generally, it is used to display a normal error message whenever an unexpected exception occurs.
Syntax
Example
Output 1 - ZeroDivisionError
D:\Python_classes>py test.py Enter First Number: 10 Enter Second Number: 0 ZeroDivisionError:Can't divide with zero
Output 2 - Any Other Exception
D:\Python_classes>py test.py Enter First Number: 10 Enter Second Number: ten Default Except:Plz provide valid input only
Explanation
With the input 10 and 0, a ZeroDivisionError is raised, so the specific except ZeroDivisionError block runs.
With the input 10 and ten, a ValueError is raised. There is no ValueError handler, so Python executes the default except block.
Execution Flow
Program Starts
│
▼
Execute try Block
│
▼
Exception Raised
│
▼
Matching Specific except ?
│
┌────┴────┐
│ │
▼ ▼
Yes No
│ │
▼ ▼
Execute Execute
Specific Default
except except
│ │
└────┬─────┘
▼
Program Continues
Important Note
If a try block has multiple except blocks, then the default except block must always be the last block.
Otherwise, Python raises a SyntaxError.
Incorrect Example
Why Does this Error Occur?
The default except block can handle every type of exception.
If it is written before specific exception handlers, those handlers will never execute.
Therefore, Python requires the default except block to be placed last.
Various Possible Combinations of except Blocks
- The default except block can handle any type of exception
- It is written as a bare except: with no exception type
- It runs only when no specific except block matches
- The default except block must always be last, or Python raises a SyntaxError
- It is commonly used to show a friendly error message for unexpected exceptions