Hack Forums
[Python] Handling Multiple Exceptions at Once? - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] Handling Multiple Exceptions at Once? (/showthread.php?tid=5604697)



Handling Multiple Exceptions at Once? - TheWarOwl - Apr 20, 2017

Hey everyone!

I just had a quick curious question, I can't seem to find any information on...

Let me give you an example - let's say I'm programming a program that communicates over a network and I want the program to "Try - Except" and "Pass" whenever a ConnectionResetError is thrown or a ConnectionTimeOut error is thrown - how can I handle both of these at once, but only those two?

If my question confuses you I could give some example code - otherwise any help is appreciated, I'm always trying to learn! Thanks!


* - Retribute - Apr 20, 2017

An except clause may name multiple exceptions as a parenthesized tuple.
PHP Code

<?php 
except 
(ConnectionResetError, ConnectionTimeOut):
    
pass 



* - TheWarOwl - Apr 20, 2017

Ah, that simple? Thank you very much.


* - Goodies - Apr 20, 2017

If you want to do different things with different errors:

PHP Code

<?php 
try:
    
exception_raising_method()
except ConnectionResetError:
    print(
"Port is closed. TCP RST Received")
except ConnectionTimeout:
    print(
"Connection Timed Out")
except Exception as e:
    print(
"{}: {}", type(e).__name__, e) 



* - hunter24957 - Apr 21, 2017

This will eliminate the need for a pass on an exception.

PHP Code

<?php 
from contextlib import suppress

with suppress
(ConnectionResetError, ConnectionTimeOut):
    
# Your code here 



* - TheWarOwl - Apr 21, 2017

(Apr 20, 2017 11:18 PM)Goodies Wrote:  If you want to do different things with different errors:

PHP Code

<?php 
try:
    
exception_raising_method()
except ConnectionResetError:
    print(
"Port is closed. TCP RST Received")
except ConnectionTimeout:
    print(
"Connection Timed Out")
except Exception as e:
    print(
"{}: {}", type(e).__name__, e) 

Cool, thank you! I didn't know you could do multiple except statements.


(Apr 21, 2017 07:37 AM)hunter24957 Wrote:  This will eliminate the need for a pass on an exception.

PHP Code

<?php 
from contextlib import suppress

with suppress
(ConnectionResetError, ConnectionTimeOut):
    
# Your code here 

You as well - Thanks for the examples. I'll use alot of this.