简体   繁体   中英

Erlang How to mix try catch with if

I'm very new in Erlang. I want to make function to check ban word.

But I got syntax errors.. How to use try catch with if else statement?

check_banword(Word, BlackWord) ->
    try 
      Res = string:rstr(Word, BlackWord),
      if Res > 0 -> 
          true;
      true ->    
          false
    catch
      false
    end.

Two problems in the code:

  1. Missing end after if
  2. Catch syntax is incorrect, catch matches exceptions to values, you cannot have just a value there.

The code with changes enabling it to compile looks like

    check_banword(Word, BlackWord) ->
      try 
        Res = string:rstr(Word, BlackWord),
        if
          Res > 0 -> 
            true;
          true ->    
            false
        end
      catch
        _ -> false
      end.

In this case, you don't actually need the if , you can use try with patterns and guards. When used in this way, try looks like a case expression with a catch section at the end. (Note that only the part between try and of is "protected" by the catch - in this case, it doesn't make any difference because the rest of the code cannot raise an error.)

Also note that you need to specify what type of exception you want to catch, one of error , exit and throw . If you don't specify the type of exception, it defaults to throw - and that's not what you want here, since string:rstr never throws anything, it can only raise errors if the arguments are of an incorrect type.

So that would be:

check_banword(Word, BlackWord) ->
  try string:rstr(Word, BlackWord) of
      Res when Res > 0 -> 
        true;
      _ ->    
        false
  catch
    error:_ -> false
  end.

And there is a wider question: should you actually use try here? If an error occurs in this function, it means that the arguments were not strings, and that is the caller's responsibility. Since there isn't anything that this function can do to fix the problem, I'd say that it shouldn't catch the error but let it propagate to the caller. (This is known as Erlang's "let it crash" philosophy.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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