Runtime exception in python

Errors and Exceptions

No matter your skill as a programmer, you will eventually make a coding mistake. Such mistakes come in three basic flavors:

  • Syntax errors: Errors where the code is not valid Python (generally easy to fix)
  • Runtime errors: Errors where syntactically valid code fails to execute, perhaps due to invalid user input (sometimes easy to fix)
  • Semantic errors: Errors in logic: code executes without a problem, but the result is not what you expect (often very difficult to track-down and fix)

Here we’re going to focus on how to deal cleanly with runtime errors. As we’ll see, Python handles runtime errors via its exception handling framework.

Runtime Errors¶

If you’ve done any coding in Python, you’ve likely come across runtime errors. They can happen in a lot of ways.

For example, if you try to reference an undefined variable:

--------------------------------------------------------------------------- NameError Traceback (most recent call last) in () ----> 1 print(Q) NameError: name 'Q' is not defined

Or if you try an operation that’s not defined:

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () ----> 1 1 + 'abc' TypeError: unsupported operand type(s) for +: 'int' and 'str'

Or you might be trying to compute a mathematically ill-defined result:

--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) in () ----> 1 2 / 0 ZeroDivisionError: division by zero

Or maybe you’re trying to access a sequence element that doesn’t exist:

--------------------------------------------------------------------------- IndexError Traceback (most recent call last) in () 1 L = [1, 2, 3] ----> 2 L[1000] IndexError: list index out of range

Note that in each case, Python is kind enough to not simply indicate that an error happened, but to spit out a meaningful exception that includes information about what exactly went wrong, along with the exact line of code where the error happened. Having access to meaningful errors like this is immensely useful when trying to trace the root of problems in your code.

Catching Exceptions: try and except ¶

The main tool Python gives you for handling runtime exceptions is the try . except clause. Its basic structure is this:

try: print("this gets executed first") except: print("this gets executed only if there is an error") 

Note that the second block here did not get executed: this is because the first block did not return an error. Let’s put a problematic statement in the try block and see what happens:

try: print("let's try something:") x = 1 / 0 # ZeroDivisionError except: print("something bad happened!") 
let's try something: something bad happened!

Here we see that when the error was raised in the try statement (in this case, a ZeroDivisionError ), the error was caught, and the except statement was executed.

One way this is often used is to check user input within a function or another piece of code. For example, we might wish to have a function that catches zero-division and returns some other value, perhaps a suitably large number like $10^$:

def safe_divide(a, b): try: return a / b except: return 1E100 

Источник

Читайте также:  Html всплывающее меню справа
Оцените статью