简体   繁体   English

如何捕获 TypeError 并打印自定义消息?

[英]How to catch TypeError and print custom message?

I am trying to create a function to check if a path exists or not, but when I call my function without any parameter it does not catch typerror and throw me an error.我正在尝试创建一个 function 来检查路径是否存在,但是当我在没有任何参数的情况下调用我的typerror时,它不会捕获打字错误并向我抛出错误。

Code:代码:

def checkPath(pathName):
    try:
        import os, sys
        try:
            if pathName.strip() == '' or pathName is None:
                raise TypeError("No parameter is passed to function : checkPathExist(pathName)")
            else:
                try:
                    if os.path.isdir(pathName):
                        print('Source path exist : ', pathName)
                    else:
                        raise Exception("Invalid Path Found : ", pathName)
                except Exception as error:
                    print('Error : ' + repr(error))
                    quit()
        except Exception as error:
            print('Error : ' + repr(error))
            quit()
    except TypeError:
        raise Exception("No argument passed ...")

    except Exception as error:
        print('Error : ' + repr(error))
        quit()

Following is the way I am calling my function without parameters.以下是我不带参数调用 function 的方式。 I want to print custom message if no parameter is passed.如果没有传递参数,我想打印自定义消息。

checkPath()

If you call your function without an argument it will throw a TypeError at the call to the function not within it.如果您在不带参数的情况下调用 function,它会在调用不在其中的 function 时抛出 TypeError。 So if you want to handle no arguments as a type error inside the function you should provide a default value for your argument and then raise the error if the default value is unchanged.因此,如果您想在 function 中将 no arguments 作为类型错误处理,您应该为您的参数提供一个默认值,然后在默认值未更改时引发错误。 Somthing like this:像这样的东西:

def checkPath(mypath = ""):

  try:
    if myPath == "":
        raise TypeError
    
    import os,sys
    
    try:

      if pathName.strip() == '' or pathName is None :
        
        raise TypeError("No parameter is passed to function : checkPathExist(pathName)")
      
      else:

        try:

          if os.path.isdir(pathName):
            
            print('Source path exist : ',pathName)
          
          else:
            
            raise Exception("Invalid Path Found : ",pathName)
        
        except Exception as error:
          
          print('Error : ' + repr(error))
          quit()

    except Exception as error:
      print('Error : ' + repr(error))
      quit()

  except TypeError:
    raise Exception("No argument passed ...")

  except Exception as error:
    print('Error : ' + repr(error))
    quit()

change the first line of function to initialize variable mypath with some default value.更改 function 的第一行以使用一些默认值初始化变量mypath Maybe None .也许None

Try this:尝试这个:

def checkPath(mypath=None):

If you dont initilize the variable, you must pass a value while calling method, else it would throw error to state you cannot call the function (1 argument is needed)如果你不初始化变量,你必须在调用方法时传递一个值,否则它会抛出错误到 state 你不能调用 function(需要 1 个参数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM