Can I catch multiple Java exceptions in the same catch clause?

This has been possible since Java 7. The syntax for a multi-catch block is: try { … } catch (IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException e) { someCode(); } Remember, though, that if all the exceptions belong to the same class hierarchy, you can simply catch that base exception type. Also note that you … Read more

Better to ‘try’ something and catch the exception or test if it’s possible first to avoid an exception?

You should prefer try/except over if/else if that results in speed-ups (for example by preventing extra lookups) cleaner code (fewer lines/easier to read) Often, these go hand-in-hand. speed-ups In the case of trying to find an element in a long list by: try: x = my_list[index] except IndexError: x = ‘NO_ABC’ the try, except is … Read more