Comparisment

   - compare programming languages by example

50

Throw exceptions

The syntax for throwing exceptions.

Created by sam

Add a new answer

Either add an answer for a new language or add an alternative solution.
A description is only necessary when the code is not suitably 'obvious' or to justify an alternative approach.

Haskell

unsafeDivide :: Int -> Int -> Int
unsafeDivide x 0 = error "Division by zero!"
unsafeDivide x y = x `div` y

'error' will cause an otherwise pure value to throw an exception when evaluated which can be caught with 'catch' from 'Control.Exception' in 'IO'. Normally, however, it would be better to opt for a more Haskell-y alternative such as using 'Maybe' or 'Either' types to explicitly denote failure that the caller may pattern match upon.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Haskell

divM :: Monad m => Int -> Int -> m Int
divM x 0 = fail "Division by zero!"
divM x y = return $ x `div` y

If your function is in any (or a specific) type which is an instance of 'Monad', you may use 'fail' in place of 'error' to delegate the specifics of how failure is handled to the monad instance. This has much of the same disadvantages as 'error'.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Haskell

safeDivide :: Int -> Int -> Maybe Int
safeDivide x 0 = Nothing
safeDivide x y = Just (x `div` y)

Instead of throwing an exception, failure is denoted by the 'Nothing' constructor and success by 'Just'. This way, we require that the caller must explicitly handle the failure case.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Haskell

safeDivide :: Int -> Int -> Either String Int
safeDivide x 0 = Left "Division by zero!"
safeDivide x y = Right (x `div` y)

Instead of throwing an exception, failure is denoted by the 'Left' constructor (which takes a failure reason as a string) and success by 'Right'. This way, we require that the caller must explicitly handler the failure case. As opposed to using a 'Maybe' type the caller is also given a reason for failure.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Haskell

data DivError = DivideByZero

safeDivide :: Int -> Int -> Either DivError Int
safeDivide x 0 = Left DivideByZero
safeDivide x y = Right (x `div` y)

Instead of throwing an exception, failure is denoted by the 'Left' constructor (which takes a failure reason as user defined data type) and success by 'Right'. This way, we require that the caller must explicitly handler the failure case. As opposed to using a 'Maybe' type the caller is also given a reason for failure which is denoted by a custom data type.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Haskell

import Control.Monad.Error

data AdmittanceError
  = TooTall
  | TooShort
  | RefusedForReason String
  | RefusedForNoReason

instance Error AdmittanceError where
  noMsg      = RefusedForNoReason
  strMsg str = RefusedForReason str

rideRollerCoaster :: MonadError AdmittanceError m => Int -> String -> m ()
rideRollerCoaster height name
  | height < 4    = throwError TooShort
  | height > 8    = throwError TooTall
  | name == "Eve" = throwError $ RefusedForReason "You're banned!"
  | otherwise     = return ()

Declare custom exception types which can be thrown with 'Control.Monad.Error's 'throwError' and caught with 'catchError'.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

def raiseAnException():
  raise Exception("I have an exception!")

Raise a very general exception. It isn't possible to catch this exception without having to handle all others and so is not recommended.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

def raiseAnException():
  raise ValueError("I have an exception!")

Raise a more specific exception type from the standard exception hierarchy.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

class IHaveAnException(Exception):
  pass

def raiseAnException():
  raise IHaveAnException("I have an exception!")

Raise a custom exception.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.