Error handling is a crucial aspect of writing robust Elixir applications. By understanding how to manage errors using try, catch, and rescue, raising custom errors with raise, and using after for cleanup, developers can create more reliable and maintainable code. This guide covers basic error handling techniques in Elixir to improve application resilience.
1. Using try, catch, rescue
In Elixir, which block is used to handle exceptions in the code?
a) catch
b) rescue
c) try
d) finally
What does the try block do in Elixir error handling?
a) Catches exceptions
b) Executes code that might raise an exception
c) Defines cleanup actions
d) Raises errors manually
How do you handle errors that occur within the try block in Elixir?
a) Using throw
b) Using rescue
c) Using catch
d) Using raise
What is the correct syntax to rescue an error from the try block in Elixir?
a) try ... rescue Exception -> ... end
b) catch ... exception -> ... end
c) try ... catch Error -> ... end
d) throw ... Exception -> ... end
Which of the following will NOT be caught by the rescue block in Elixir?
a) Runtime exceptions
b) Compile-time errors
c) Arithmetic errors
d) Custom exceptions
Which statement is true about the catch block in Elixir?
a) It handles both exceptions and errors.
b) It handles only system-level errors.
c) It is not used for exception handling.
d) It is used to catch non-local returns and errors.
What is the role of the try block in Elixir?
a) It defines a section of code where errors can be raised.
b) It executes code in the background while handling errors.
c) It catches errors that occur within the block.
d) It ensures that exceptions are not thrown in the code.
Which of the following is a valid way to handle errors in Elixir?
a) try ... catch
b) try ... rescue
c) try ... throw
d) try ... finally
2. Raising Errors with raise
Which function is used to raise errors in Elixir?
a) throw
b) raise
c) catch
d) exit
What is the default exception type raised by the raise function in Elixir if no argument is provided?
a) RuntimeError
b) Error
c) Exception
d) RuntimeException
What argument is needed to raise a custom exception in Elixir using raise?