0

I am trying to enter the exception part after the try statement. Here is my code

user_date = user.datetime
    try:
        user_date == None
        print(user_date)
    except Exception as e:
        raise Unauthorized(f"Not a date")

the print statement returns 2022-08-22 18:12:53.409212 so that is working correctly. But that means user_date does not equal none. Shouldn't this enter the exception?

Expected output is that it enters the exception since user_date = user.datetime is not None

I would use an if statement except I need to raise an exception without exiting the function.

Thanks in advance.

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • 1
    This is not how exceptions work. It seems you are looking for an `if` statement or an `assert`. – Axe319 Aug 23 '22 at 17:20
  • 1
    `user_date == None` is not raising an exception nor will it ever raise one. You are ignoring the result of the comparison entirely. – Martijn Pieters Aug 23 '22 at 17:20
  • 1
    Instead of `try...except`, why not use `if user_date is None: raise Unauthorized("Not a date")`? – Martijn Pieters Aug 23 '22 at 17:21
  • I can't do a normal if statement because I need the function to continue even after the exception is raised – user19701195 Aug 23 '22 at 17:23
  • Which function needs to continue? The only one in your example is the built-in `print` function. – Axe319 Aug 23 '22 at 17:28
  • @Axe319 the code is within a larger function and it needs to exceed regardless if the exception is reached or not – user19701195 Aug 23 '22 at 17:29
  • A few things: `if user_date is None: raise Unauthorized("Not a date")` is raising an exception. Having your code within a `try`/`except` also means execution inside the `try` block will stop at the point the exception is raised. If a conditional Exception will not work for your scenario you'll need to include a short example where it will not so we can find a solution for it. – Axe319 Aug 23 '22 at 17:35

0 Answers0