Exception Handling in .NET F# Dr. Rajeshree Khande
Topics to be Covered….  Exception Handling Basics  Try/With  Raising Exceptions  Try/Finally  use Statement  Exception Handling Constructs
Exception Handling Basics  Exception handling is the standard way of handling error conditions  An exception is an object that encapsulates information about an error.  When errors occur, exceptions are raised and regular execution stops.
Exception Handling Basics  An exception is a problem that arises during the execution of a program.  Example such as an attempt to divide by zero.  Exceptions provide a way to transfer control from one part of a program to another.
Exception Handling Basics  Instead, the runtime searches for an appropriate handler for the exception.  The search starts in the current function, and proceeds up the stack through the layers of callers until a matching handler is found.  Then the handler is executed.
Exception Handling Basics let getNumber msg = printf msg; int32(System.Console.ReadLine()) let x = getNumber("x = ") let y = getNumber("y = ") printfn "%i + %i = %i" x y (x + y) This code is syntactically valid, and it has the correct types. However, it can fail at run time if we give it a bad input: x = 7 y = monkeys! ------------ FormatException was unhandled. Input string was not in a correct format.
Exception Handling : Basic Syntax exception exception-type of argument- type name of a new F# exception type. type of an argument that can be supplied when you raise an exception Multiple arguments can be specified by using a tuple type for argument-type.
Exception Handling : try…with  The try...with expression is used for exception handling try expression1 with | pattern1 -> expression2 | pattern2 -> expression3 ...
Exception Handling : try…with let divprog x y = try Some (x / y) with | :? System.DivideByZeroException -> printfn "Division by zero!"; None let result1 = divprog 100 0 :? exception- type Matches the specified .NET exception type.
Exception Handling : try…finally  The try...finally expression allows you to execute clean-up code even if a block of code throws an exception. try expression1 finally expression2.
Raising Exceptions  The raise function is used to indicate that an error or exceptional condition has occurred.  It also captures the information about the error in an exception object.  There are several standard functions for raising exceptions:
Raising Exceptions 1. raise function raise (expression) 2. failwith function generates an F# exception. failwith error-message-string 3. invalidArg function generates an argument exception. invalidArg parameter-name error-message- string
Example  Demonstration of try…with and raise exception
exception Error1 of string // Using a tuple type as the argument type. exception Error2 of string * int let myfunction x y try if x = y then raise (Error1("Equal Number Error")) else raise (Error2("Error Not detected", 100)) with | Error1(str) -> printfn "Error1 %s" str | Error2(str, i) -> printfn "Error2 %s %d" str I myfunction 20 10 Error2 Error Not detected 100 Error1 Equal Number Error
Example Demonstration failwith exception
let divisionFunc x y = if (y = 0) then failwith "Divisor cannot be zero." else x / y let trydivisionFunc x y = try divisionFunc x y with | Failure(msg) -> printfn "%s" msg; 0 let result1 = trydivisionFunc 100 0 let result2 = trydivisionFunc 100 4 printfn "%A" result1 Divisor cannot be zero. 0 25 O/P
Example invalidArg The invalidArg function generates an argument exception.
let days = [| "Sunday"; "Monday"; "Tuesday"; "Wednesday"; "Thursday"; "Friday"; "Saturday" |] let findDay day = if (day > 7 || day <= 1) then invalidArg "day" (sprintf "You have entered %d." day) days.[day - 1] printfn "%s" (findDay 1) printfn "%s" (findDay 5) printfn "%s" (findDay 9) Sunday Thursday Unhandled Exception: System.ArgumentException: You have entered 9. Parameter name: day …… O/P
Example try…with & try…finally
let divide x y= try try (x+1) / y finally printf "this will always be printed" with | :? System.DivideByZeroException as ex -> printfn "%s" ex.Message; 0 divide 10 5
Exception type Description Example Exception Base class for all exceptions. None (use a derived class of this exception). IndexOutOfRangeException Thrown by the runtime only when an array is indexed improperly. Indexing an array outside its valid range: arr[arr.Length+1] NullReferenceException Thrown by the runtime only when a null object is referenced. object o = null; o.ToString(); InvalidOperationException Thrown by methods when in an invalid state. Calling Enumerator.MoveNext() after removing an item from the underlying collection. ArgumentException Base class for all argument exceptions. None (use a derived class of this exception). ArgumentNullException Thrown by methods that do not allow an argument to be null. String s = null; "Calculate".IndexOf(s); ArgumentOutOfRangeExcepti on Thrown by methods that verify that arguments are in a given range. String s = "string"; s.Substring(s.Length+1);

Exception Handling in .NET F#

  • 1.
  • 2.
    Topics to beCovered….  Exception Handling Basics  Try/With  Raising Exceptions  Try/Finally  use Statement  Exception Handling Constructs
  • 3.
    Exception Handling Basics Exception handling is the standard way of handling error conditions  An exception is an object that encapsulates information about an error.  When errors occur, exceptions are raised and regular execution stops.
  • 4.
    Exception Handling Basics An exception is a problem that arises during the execution of a program.  Example such as an attempt to divide by zero.  Exceptions provide a way to transfer control from one part of a program to another.
  • 5.
    Exception Handling Basics Instead, the runtime searches for an appropriate handler for the exception.  The search starts in the current function, and proceeds up the stack through the layers of callers until a matching handler is found.  Then the handler is executed.
  • 6.
    Exception Handling Basics letgetNumber msg = printf msg; int32(System.Console.ReadLine()) let x = getNumber("x = ") let y = getNumber("y = ") printfn "%i + %i = %i" x y (x + y) This code is syntactically valid, and it has the correct types. However, it can fail at run time if we give it a bad input: x = 7 y = monkeys! ------------ FormatException was unhandled. Input string was not in a correct format.
  • 7.
    Exception Handling :Basic Syntax exception exception-type of argument- type name of a new F# exception type. type of an argument that can be supplied when you raise an exception Multiple arguments can be specified by using a tuple type for argument-type.
  • 8.
    Exception Handling :try…with  The try...with expression is used for exception handling try expression1 with | pattern1 -> expression2 | pattern2 -> expression3 ...
  • 9.
    Exception Handling :try…with let divprog x y = try Some (x / y) with | :? System.DivideByZeroException -> printfn "Division by zero!"; None let result1 = divprog 100 0 :? exception- type Matches the specified .NET exception type.
  • 10.
    Exception Handling :try…finally  The try...finally expression allows you to execute clean-up code even if a block of code throws an exception. try expression1 finally expression2.
  • 11.
    Raising Exceptions  Theraise function is used to indicate that an error or exceptional condition has occurred.  It also captures the information about the error in an exception object.  There are several standard functions for raising exceptions:
  • 12.
    Raising Exceptions 1. raisefunction raise (expression) 2. failwith function generates an F# exception. failwith error-message-string 3. invalidArg function generates an argument exception. invalidArg parameter-name error-message- string
  • 13.
    Example  Demonstration oftry…with and raise exception
  • 14.
    exception Error1 ofstring // Using a tuple type as the argument type. exception Error2 of string * int let myfunction x y try if x = y then raise (Error1("Equal Number Error")) else raise (Error2("Error Not detected", 100)) with | Error1(str) -> printfn "Error1 %s" str | Error2(str, i) -> printfn "Error2 %s %d" str I myfunction 20 10 Error2 Error Not detected 100 Error1 Equal Number Error
  • 15.
  • 16.
    let divisionFunc xy = if (y = 0) then failwith "Divisor cannot be zero." else x / y let trydivisionFunc x y = try divisionFunc x y with | Failure(msg) -> printfn "%s" msg; 0 let result1 = trydivisionFunc 100 0 let result2 = trydivisionFunc 100 4 printfn "%A" result1 Divisor cannot be zero. 0 25 O/P
  • 17.
    Example invalidArg The invalidArg functiongenerates an argument exception.
  • 18.
    let days =[| "Sunday"; "Monday"; "Tuesday"; "Wednesday"; "Thursday"; "Friday"; "Saturday" |] let findDay day = if (day > 7 || day <= 1) then invalidArg "day" (sprintf "You have entered %d." day) days.[day - 1] printfn "%s" (findDay 1) printfn "%s" (findDay 5) printfn "%s" (findDay 9) Sunday Thursday Unhandled Exception: System.ArgumentException: You have entered 9. Parameter name: day …… O/P
  • 19.
  • 20.
    let divide xy= try try (x+1) / y finally printf "this will always be printed" with | :? System.DivideByZeroException as ex -> printfn "%s" ex.Message; 0 divide 10 5
  • 21.
    Exception type DescriptionExample Exception Base class for all exceptions. None (use a derived class of this exception). IndexOutOfRangeException Thrown by the runtime only when an array is indexed improperly. Indexing an array outside its valid range: arr[arr.Length+1] NullReferenceException Thrown by the runtime only when a null object is referenced. object o = null; o.ToString(); InvalidOperationException Thrown by methods when in an invalid state. Calling Enumerator.MoveNext() after removing an item from the underlying collection. ArgumentException Base class for all argument exceptions. None (use a derived class of this exception). ArgumentNullException Thrown by methods that do not allow an argument to be null. String s = null; "Calculate".IndexOf(s); ArgumentOutOfRangeExcepti on Thrown by methods that verify that arguments are in a given range. String s = "string"; s.Substring(s.Length+1);