Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6631243
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T22:31:05+00:00 2026-05-25T22:31:05+00:00

Should I test if something is valid or just try to do it and

  • 0

Should I test if something is valid or just try to do it and catch the exception?

  • Is there any solid documentation saying that one way is preferred?
  • Is one way more pythonic?

For example, should I:

if len(my_list) >= 4:
    x = my_list[3]
else:
    x = 'NO_ABC'

Or:

try:
    x = my_list[3]
except IndexError:
    x = 'NO_ABC'

Some thoughts…
PEP 20 says:

Errors should never pass silently.
Unless explicitly silenced.

Should using a try instead of an if be interpreted as an error passing silently? And if so, are you explicitly silencing it by using it in this way, therefore making it OK?


I’m not referring to situations where you can only do things 1 way; for example:

try:
    import foo
except ImportError:
    import baz
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T22:31:06+00:00Added an answer on May 25, 2026 at 10:31 pm

    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 the best option when the index is probably in the list and the IndexError is usually not raised. This way you avoid the need for an extra lookup by if index < len(my_list).

    Python encourages the use of exceptions, which you handle is a phrase from Dive Into Python. Your example not only handles the exception (gracefully), rather than letting it silently pass, also the exception occurs only in the exceptional case of index not being found (hence the word exception!).


    cleaner code

    The official Python Documentation mentions EAFP: Easier to ask for forgiveness than permission and Rob Knight notes that catching errors rather than avoiding them, can result in cleaner, easier to read code. His example says it like this:

    Worse (LBYL ‘look before you leap’):

    #check whether int conversion will raise an error
    if not isinstance(s, str) or not s.isdigit():
        return None
    elif len(s) > 10:    #too many digits for int conversion
        return None
    else:
        return int(s)
    

    Better (EAFP: Easier to ask for forgiveness than permission):

    try:
        return int(s)
    except (TypeError, ValueError, OverflowError): #int conversion failed
        return None
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

What Makes a Good Unit Test? says that a test should test only one
I don't know if I should test my @Entity-annotated Pojos. After all, there are
I want that my unit tests to cover my POCO's. How should I test
I have an issue with watin test that should browse for pdf and upload
I am wondering should I write unit test for everything. There are some classes
If I want to test that a method throws an exception of a particular
I was wondering whether the object to test should be a field and thus
When hiring a front-end developer, what specific skills and practices should you test for?
Duplicate: Why should I practice Test Driven Development and how should I start? For
In .NET should you place unit test projects in with the rest of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.