![]() Here’s how you can catch the error and print it to your shell: try: This is the case if the object doesn’t define the _getitem_() method. ![]() ![]() Python throws the TypeError object is not subscriptable if you use indexing with the square bracket notation on an object that is not indexable. math domain errorĪm I executed? Example 3: Catch and Print TypeError The output shows that not only the error message but also the string 'Am I executed?' is printed. Here’s an example where the ValueError is raised because you tried to calculate the square root of a negative number: import math The ValueError arises if you try to use wrong values in some functions. □ Recommended Tutorial: How to Print an Error in Python? Example 2: Catch and Print ValueError This is the output of the previous code snippet. Thus, it executes the final print() statement after the exception has been caught and handled. Your genius code attempts to access the fourth element in your list with index 3-that doesn’t exist!įortunately, you wrapped the code in a try/catch block and printed the exception. If you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an Inde圎rror telling you that the list index is out of range. You can now print the error message with "print(e)" or use it for further processing. To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e. Here’s how you catch and print a given exception: To avoid this, you can catch the exception with a try/except block around the code where you expect that a certain exception may occur. The most popular examples are the Inde圎rror, ValueError, and TypeError.Īn exception will immediately terminate your program. An exception event interrupts and, if uncaught, immediately terminates a running program. Python comes with an extensive support of exceptions and exception handling.
0 Comments
Leave a Reply. |