Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Python 

Handling Multiple Exceptions at Once?

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!
[Image: 5BgQiIm.gif]

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

<?php 
except 
(ConnectionResetError, ConnectionTimeOut):
    
pass 
[Image: npafFhp.gif]
Ah, that simple? Thank you very much.
[Image: 5BgQiIm.gif]

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) 
SRPP Discord Server

I am a professional network/cloud security architect.
My Old Tutorials
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 
(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.
[Image: 5BgQiIm.gif]



Possibly Related Threads...
Thread / Author Replies Views Last Post
[C#] by john ronaldsadJul 20, 2022 06:49 PM 4 238 Jul 20, 2022 06:49 PM
Last Post: john ronaldsad
[Python] by Robin2Jan 13, 2019 06:27 AM 2 123 Jan 13, 2019 06:27 AM
Last Post: lockhead
[C#] by gigajewSep 13, 2018 03:36 PM 26 843 Sep 13, 2018 03:36 PM
Last Post: ppaida