Skip to content

Latest commit

 

History

History
203 lines (155 loc) · 4.26 KB

day_6.md

File metadata and controls

203 lines (155 loc) · 4.26 KB

Erlang tutorial day 6

Table of Contents

  1. Compile-time errors
  2. Logical errors
  3. Run-time errors
  4. Exceptions
  5. Error logging
  6. Exercises
  7. Readings

1 Compile-time errors

List of compilation errors

Example code (no_module.erl, syntax_error.erl, warnings.erl)

1> c(no_module).
no_module.erl:1: no module definition
error

2> c(syntax_error).
syntax_error.erl:3: syntax error before: '.'
error

3> c(warnings).
warnings.erl:3: Warning: function unused_fun/1 is unused
warnings.erl:3: Warning: variable 'UnusedVar' is unused
{ok, warnings}

2 Logical errors

Example code (logical_error.erl)

1> c(logical_error).
{ok,logical_error}
2> logical_error:fibonacci(6).
8
3> logical_error:fibonacci(-1).
...
^C

Preventions:

  • eunit, ct (common test), ...

3 Run-time errors

1> {ok, Result} = {ok, some, return_value}.
** exception error: no match of right hand side value {ok,some,return_value}
1> lists:magical_sort([1,2,3,2,1]).
** exception error: undefined function lists:magical_sort/1

4 Exceptions

4.1 Classes (error, exit, throw)

1> error(badarith).
** exception error: an error occurred when evaluating an arithmetic expression

2> error(my_error).
** exception error: my_error

3> exit(exception).
** exception exit: exception

4> throw(exception).
** exception throw: exception

Source code of throw module

1> Map = #{key1 => value1}.
#{key1 => value1}
2> maps:get(key1, Map).
value1
3> maps:get(key2, Map).
** exception error: {badkey,key2}
     in function  maps:get/2
        called as maps:get(key2,#{key1 => value1})
4> throw:get_from_map(key1, Map).
value1
5> throw:get_from_map(key2, Map).
undefined

4.2 Type specification

no_return()
no_return() | integer() % this will be integer()

4.3 Handling

1> try 1/0
   catch
     error:badarith -> infinity
   end.
infinity
2> try 1/1 of
     1 -> {ok, 1}
   catch
     Class:Reason -> {Class, Reason}
   end.
{ok, 1}
try function_may_raise_exception() of
  Val1 -> ...;
  Val2 -> ...;
  ...
catch
  Class1:Reason1 -> ...;
  Class2:Reason2 -> ...;
  ...
after % this always gets executed and this block will not return anything
  ...
end.

5 Error logging

5.1 Info message

1> error_logger:info_msg("What is love?").
ok

=INFO REPORT==== 1-Jan-1900::00:00:01 ===
What is love?

5.2 Warning message

2> error_logger:warning_msg("Baby don't hurt me! Don't hurt me!").
ok

=WARNING REPORT==== 1-Jan-1900::00:00:02 ===
Baby don't hurt me! Don't hurt me!

5.3 Error message

3> error_logger:error_msg("No more!").
ok

=ERROR REPORT==== 1-Jan-1900::00:00:03 ===
No more!

6 Exercises

7 Readings