The document discusses exception handling in .NET F# including try/with, try/finally, raising exceptions, and common exception types. It provides examples of handling different exceptions using try/with blocks and raising custom exceptions. The key constructs for exception handling in F# are covered including basic syntax, matching exception patterns, and ensuring cleanup code executes.
2. Topics to be Covered….
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
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.
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
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:
12. 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
14. 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
16. 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
20. 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
21. 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);