Basically, in any code you write, try: except blocks can catch errors only for lines passing inside them. If you cause an error in the function call (or code that actually wraps the try: except block), the error is executed before testing, and therefore the error cannot be detected there.
That is why in order to catch the error caused by the argument before it is passed to the function (or the syntax of the function call itself), as in call_main(y) , the error handling must be moved beyond this as shown by others, here with code:
try: call_main(y) except NameError: print("exception caught a NameError")
Exception handling can only do so much. At some point, the programmer must confirm his code and make sure that it works. In an appropriate note, it is best to include a general exception try: except in your try: except blocks in order to catch any unexpected errors that you have not tested or thought of yet. The following modification of your code demonstrates this, and also shows how to get the computer to tell you what error it caught:
def call_main (list_name): try: x = first_duplicate(list_name) if x is None: print("No duplicates") else: print(x, "is the first duplicate") except NameError: print("exception occurred Name ") except ValueError: print("exception occurred value") except Exception as ee: print(ee) print(type(ee))
In the last note, to prove that your exception handling works, make the following changes to x = first_duplicate(list_name) and run it.
x = first_duplicate(y)
Result: the code catches a name error
x = first_duplicate(0)
Result: a general exception is found and the type of error is identified for you
source share