w3resource

How do you handle exceptions while debugging with 'pdb'?

Handling Exceptions with 'pdb' in Python Debugging

Debugging with 'pdb' (Python Debugger) requires handling exceptions in order to identify and diagnose errors in your code. 'pdb' provides several commands and techniques to manage exceptions during debugging and proceed with the debugging process. Here's how to handle exceptions with 'pdb':

Starting debugging with 'pdb':

Insert pdb.set_trace() at the point in our code where we want to start debugging. When an exception occurs, execution will pause at this point, and we'll enter the 'pdb' debugging mode.

Continuing execution after an exception:

When an exception occurs and the program halts at the pdb.set_trace() statement, we can continue execution using the c (continue) command. This allows us to see the error message and the traceback that led to the exception.

Print the exception:

Use the p (print) command followed by the special variable exception to print the exception details. This will show us the type and message of the exception.

Example:

(Pdb) p __exception__
<class 'ZeroDivisionError'>

Inspecting the Stack Trace:

Use the w (where) command to display the stack trace, which shows the chain of function calls that led to the exception. In this way, the context in which the exception occurred can be identified.

Example:

(Pdb) w
  /path/to/your/script.py<module>()
-> z = divide(x, y)

Inspecting the Stack Trace:

Use the w (where) command to display the stack trace, which shows the chain of function calls that led up to the exception. In this way, the context of the exception can be identified.

Example:

(Pdb) w
  /path/to/your/script.py(6)<module>()
-> z = divide(x, y)

Handling Exceptions Manually:

You can use the 's' (step into) command to step into a function that may raise an exception. In this way, you can manually handle the exception within the function.

Ignoring Exceptions:

If you want to ignore an exception and continue debugging, you can use the ignore command followed by the exception type and the number of times you would like to ignore it.

Example:

(Pdb) ignore ZeroDivisionError 2

Setting Breakpoints for Exceptions:

To set a breakpoint for a specific exception type, use the b (break) command with the exception keyword.

Example:

(Pdb) b exception ZeroDivisionError

Controlling Exception Breakpoints:

You can use the 'commands' command with breakpoint numbers to specify actions to be taken when a breakpoint is hit.

Example:

(Pdb) commands 1
(Pdb) ignore
(Pdb) c


Follow us on Facebook and Twitter for latest update.