Python syntax for raising and catching exception, also which exception type to raise

50 views Asked by At

I'm trying to learn how to work with exceptions in Python. I'm clearly misunderstanding something. It feels like there is a small thing I'm not seeing, so I feel a bit silly ;) I've looked at many threads and tutorials on this. I'm certain I'm close to doing it right, but a little wrong has pretty much the same effect as completely wrong. ;)

Here's a minimum example:

def MyFun():
    print("start MyFun")
    if True:   
        raise Exception("MyFun FAIL")
    print("not here in MyFun")
    return

try:
    MyFun()
except Exception("MyFun FAIL") as e:
    print("some message")

MyFun() always raises an exception, and I want to catch it. When I run this in my interpreter, I get "TypeError: catching classes that do not inherit from BaseException is not allowed".

I've changed Exception("MyFun FAIL") to ValueError("MyFun FAIL") just for trying stuff, but get the same message. I don't understand what I'm supposed to do.

In addition, I fail to understand what Exception type I'm supposed to raise. I found this but it doesn't do a very good job explaining what I should pick when. A general description could be helpful for the future. Short term: In my actual case, I intend to read a particular file, and if a certain text string isn't found in it, I know it's not the expected file or it's corrupted, so I want to raise an exception that I can catch and handle in the rest of my code.

Thanks for your time.

EDIT: all right, I see the comment, it doesn't crash if I do:

def MyFun():
    print("start MyFun")
    if True:   
        raise Exception("MyFun FAIL")
    print("not here in MyFun")
    return

try:
    MyFun()
except Exception as e:
    print("some message")

Yet, this doesn't answer my whole question. I know it is not explicit in the original wording, but I didn't want to catch general Exception. I want to adhere to good coding practice not to hide bugs, so I want to raise and catch specific things, and make my code respond in specific ways to these specific things.

Things not answered yet:

  1. How do I specifically do something specifically for error "MyFun FAIL" and let the program crash if I get error "whatever else caused by something else"?
  2. Which more specific exception type am I supposed to raise when the file does not have the expected contents?
0

There are 0 answers