Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (47.6k 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?

try:

 shutil.rmtree(path)

except:

  pass

1 Answer

0 votes
by (106k 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:

try:

shutil.rmtree(path)

except OSError:

Pass

  • shutil.rmtree is an OSError:

shutil.rmtree("/fake/dir")

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.

    try:

   shutil.rmtree(path)

except OSError, e:

   if e.errno == 2:

       # suppress "No such file or directory" error

       pass

   else:

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

       raise

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...