Javatpoint Logo
Javatpoint Logo

Python Built-in Exceptions

In Python, every instance must belong to a class that inherits from Base Exception. Even though they share identical name, two exception classes that are neither connected through subclassing are never equal. The interpreter or built-in methods may produce the built-in exceptions

When mistakes happen, a number of built-in exceptions in Python are raised. There have been a number of built-in exceptions in Python that you can always raise and deal with in any code. Some of the most popular built-in exceptions are listed below:

1. BaseException

The foundation class for all exceptions in Python is called BaseException. The parent class for all other exception classes in the Python Standard Library, it is a built-in class. It offers the fundamental framework for all exceptions and serves as the basis for developing unique exceptions.

The following are some of the characteristics and methods of BaseException:

  • args: A tuple of all arguments that were given to the exception when it was raised.
  • with_traceback: A method called _traceback enables you to add a traceback to an error.
  • __str__: A function that delivers the exception as a string is called __str__.

Example:

Code

Output:

CustomException                           Traceback ( most recent call last )
Input In [ 1 ], in < cell line  : 8>( )
      5     def __str__( self ) :
      6         return self.message
----  > 8 raise CustomException("  This is a custom exception. ")

CustomException  : This is a custom exception.

2. exception Exception

All Python exceptions derive from this basic class. It serves as the parent class for all of the language's other built-in exceptions. You can derive from the Exception class if you wish to design your own unique exception. Because of this, handling your custom exception in the same way as built-in exceptions is simple to do. It is recommended that all user-defined exceptions originate from this class.

Example:

Code

Output:

A custom exception was raised  : This is a custom exception.

3. AttributeError

Whenever an attribute reference or assignment failed, this exception would be thrown. When you attempt to access a property or method that isn't present on an object, this usually happens.

Example:

Code

Output:

An attribute error occurred : ' MyClass  ' object has no attribute ' non_existent_attribute '

4. TypeError

When a Python action or function is used on an object of an incorrect type, the TypeError exception is thrown. This frequently happens when you attempt to call a function with the incorrect parameter type or implement an operation on an object that has the incorrect type.

Example:

Code

Output:

A type error occurred : can only concatenate str (not " int ") to str

5. ValueError

When such an argument to a built-in method or functions has the correct type but the incorrect value because no other exception more specifically describes the circumstance, the ValueError exception is triggered in Python.

Example:

Code

Output:

A value error occurred : invalid literal for int() with base 10 : ' a '

6. KeyError

Whenever a dictionary is searched in Python with a key that really doesn't exist, the KeyError exception would be thrown.

Example:

Code

Output:

A key error occurred : ' c ' 

7. IndexError

This exception is raised when an index is out of range. Whenever a list is accessed in Python with just an index that is outside of bounds, the IndexError exception is thrown.

Example:

Code

Output:

 An index error occurred : list index out of range

8. FileNotFoundError

This exception is raised when a file or directory is requested, but the specified file or directory does not exist. When a file that should be read, accessed, or retrieved doesn't exist, Python throws the FileNotFoundError exception.

Example:

Code

Output:

A file not found error occurred: [ Errno 2 ] No such file or directory : ' myfile.txt '

9. ImportError

This exception is raised when an import statement fails. The ImportError exception is triggered in Python whenever a package or module can indeed be imported.

Example:

Code

Output:

An import error occurred : No module named ' nonexistent_module '

10. ArithmeticError

Whenever an arithmetic operation (such dividing by zero or calculating the square root of a negative integer) fails, Python's built-in ArithmeticError exception is triggered. The foundation class for more specialised arithmetic errors, such as OverflowError and ZeroDivisionError, is called ArithmeticError.

Example:

Code

Output:

An arithmetic error occurred : division by zero

11. OverflowError

Whenever an arithmetic operation yields a result that is simply too big to be represented, Python's built-in OverflowError exception is triggered. When the outcome of a mathematical functions exceeds the highest representable integer, this exception, a subclasses of ArithmeticError, is produced.

Example:

Code

12. SyntaxError

When the Python interpreter comes across a syntax issue in your code, the built-in exception SyntaxError is triggered. A syntax error happens when the code violates the syntax requirements of the Python programming language, such as when reserved words are used improperly, indentation is used incorrectly, or quotations are used incorrectly.

Code

Output:

SyntaxError : invalid syntax

13. AssertionError

Whenever an assert statement failures, the built-in Python exception known as AssertionError is thrown. An assert declaration is employed to verify for condition that have to be true in order for the process to proceed. An AssertionError exception is thrown if the condition stated in the assert statement is untrue.

Example:

Code

Output:

AssertionError: x is not greater than 10

14. FloatingPointError

Whenever an operation involving floating-point integers yields an undefinable or pointless mathematical conclusion, the FloatingPointError exception is triggered as a built-in feature of Python. When one division by zero is performed or when a value is either too big or too tiny to be expressed as a floating-point number, this can happen.

Code

Output:

nan

15. EOFError

Whenever the end-of-file (EOF) marker is encountered and there is no further data to somehow be read, Python's built-in EOFError exception is triggered. When retrieving the contents of a file, a socket, or another input stream, this may happen.

Example:

Code

Output:

EOFError : EOF when reading a line

Here's an example that demonstrates how to raise and handle different built-in exceptions:

Code

Output:

An index error occurred : list index out of range
A division by zero error occurred: division by zero
A value error occurred : invalid literal for int( ) with base 10 : ' hello '

In this example, the first try block raises an IndexError exception, which is caught and handled by the except block. The second try block raises a ZeroDivisionError exception, which is also caught and handled by the except block. The third try block raises a ValueError exception, which is caught and handled by the except block.

This demonstrates how you can raise and handle different built-in exceptions in Python, and how you can write specific exception handlers for each type of exception. By using exception handling, you can write robust code that can gracefully handle errors and exceptions, and provide meaningful error messages to the user.


Next TopicPython List Size





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA