代码之家  ›  专栏  ›  技术社区  ›  user1580348

如果发生异常或发生特定条件,则执行except部分

  •  0
  • user1580348  · 技术社区  · 5 年前

    我想执行 except 部分 或者如果 (res=1) 或者 如果DoSomething创建异常:

    try
      res := DoSomething;
    except      
      DoExceptionCode;      
    end;
    

    我怎样才能做到这一点?

    1 回复  |  直到 5 年前
        1
  •  3
  •   Remy Lebeau    5 年前

    一个 except 只有在 try 封锁。所以,如果 DoSomething() 不引发异常,只引发自己的异常,例如:

    try
      res := DoSomething;
      if res = 1 then raise Exception.Create('error message');
    except
      DoExceptionCode;
    end;
    

    否则,请改为执行以下操作:

    try
      res := DoSomething;
    except      
      res := 1;
    end;
    if res = 1 then
      DoErrorCode;