carbaretta
carbaretta

Reputation: 324

How to handle time library exceptions?

I'm currently working on a project where it is critical that i can demonstrate how a program should behave in case an error occurs. In this instance, i want my program to except any errors that may be produced by a failed time.localtime() call.

I understand that an error like this is highly unlikely to occur. Regardless, I would like to cover all possibilities. Therefore, what type of error would occur if my program was unable to get a response from time.time() or time.localtime()?

try:
   time = time.time()
except #nameoferror:
   print ("Unable to get current time")

What could i replace "#nameoferror" with in order to output the message if the time function failed?

Upvotes: 1

Views: 136

Answers (1)

ffej
ffej

Reputation: 73

EDIT: I recommend you check out this post/answer as well.

This is an interesting question! Usually, when you're writing a try/except, you'd catch the exception type that would be thrown if the error that you're anticipating occurs (as I think you already know).

For example: let's say we have variable var1, and it happens to be equal to string value of "hello". If you ran var2 = int(var1)), Python would throw a ValueError exception. Because you may expect that, you could write something like:

var1 = "hello"

try:
    int(var1)
except ValueError:
    print("Invalid casting attempt on non-numeric value.")

In your case, you are dealing something that is very unlikely (if ever) to happen. To handle cases like this, you can write generic except handling. This way, you are not catching a particular type of exception. You are catching any exception that may be thrown as a result of the attempted logic.

Example:

var1 = "hello"

try:
    time = time.time()
except:
    print("Error occurred during try statement.")
    # return value if this is part of a function/handling of your choice

Perhaps others will have a better example, but this is how I would handle an exception if I am unsure of what particular type may be thrown.

Upvotes: 1

Related Questions