UNIT-V - Part-1 (Error and Exceptions)
UNIT-V - Part-1 (Error and Exceptions)
UNIT-V - Part-1 (Error and Exceptions)
Solving
Ex:
amount = 10000
if(amount>2999)
print(“Hello”)
Output:
File "<ipython-input-2-a0933a876a76>", line 2
if(amount>2999)
^
SyntaxError: invalid syntax
Ex:
print(dir(locals()['__builtins__']))
RuntimeError Raised when an error does not fall under any other category.
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied to an object of incorrect type.
ValueError Raised when a function gets argument of correct type but improper value.
• Python also allows you to create your own exceptions by deriving classes
from the standard built-in exceptions.
• In Python, users can define such exceptions by creating a new class.
• This exception class has to be derived, either directly or indirectly,
from Exception class.
Syntax:
class user_defiend_exception_class_name(Exception):
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
Enter a number: 12
This value is too large, try again!
Enter a number: 0
This value is too small, try again!
Enter a number: 8
This value is too small, try again!
Enter a number: 10
Congratulations! You guessed it correctly.