0 votes
1 view
in Python by (47.8k points)

When you just want to do a try-except without handling the exception, how do you do it in Python?

Is the following the right way to do it?





1 Answer

0 votes
by (107k points)

You can use the following methods to ignore exceptions properly:-

  • shutil.rmtree(path[, ignore_errors[, onerror]])

It deletes an entire directory argument ‘path’ must point to a directory. If the argument is true, if errors are false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception in that case.

You can explicitly check for the path is a symbolic link and raise OSError in that

  • If you want to ignore that error, you need to do:



except OSError:


  • shutil.rmtree is an OSError:


Traceback (most recent call last):

OSError: [Errno 2] No such file or directory: '/fake/dir'

  • If you want to write much better code, then exceptions can be handled using the OSError exception.



except OSError, e:

   if e.errno == 2:

       # suppress "No such file or directory" error



       # reraise the exception, as it's an unexpected error


Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !