SlideShare a Scribd company logo
1 of 21
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);

More Related Content

What's hot

JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingPathomchon Sriwilairit
 
Chapter 9.3
Chapter 9.3Chapter 9.3
Chapter 9.3sotlsoc
 
Python - Control Structures
Python - Control StructuresPython - Control Structures
Python - Control StructuresLasithNiro
 
Logical and Conditional Operator In C language
Logical and Conditional Operator In C languageLogical and Conditional Operator In C language
Logical and Conditional Operator In C languageAbdul Rehman
 
Visula C# Programming Lecture 4
Visula C# Programming Lecture 4Visula C# Programming Lecture 4
Visula C# Programming Lecture 4Abou Bakr Ashraf
 
operators and control statements in c language
operators and control statements in c languageoperators and control statements in c language
operators and control statements in c languageshhanks
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in cMemo Yekem
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statementnarmadhakin
 
Chapter 4.4
Chapter 4.4Chapter 4.4
Chapter 4.4sotlsoc
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Neeru Mittal
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
C programming
C programmingC programming
C programmingXad Kuain
 

What's hot (20)

C++ ala
C++ alaC++ ala
C++ ala
 
Matlab Script - Loop Control
Matlab Script - Loop ControlMatlab Script - Loop Control
Matlab Script - Loop Control
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
 
Chapter 9.3
Chapter 9.3Chapter 9.3
Chapter 9.3
 
43c
43c43c
43c
 
M C6java5
M C6java5M C6java5
M C6java5
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
 
Python - Control Structures
Python - Control StructuresPython - Control Structures
Python - Control Structures
 
Logical and Conditional Operator In C language
Logical and Conditional Operator In C languageLogical and Conditional Operator In C language
Logical and Conditional Operator In C language
 
Visula C# Programming Lecture 4
Visula C# Programming Lecture 4Visula C# Programming Lecture 4
Visula C# Programming Lecture 4
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
 
07 flow control
07   flow control07   flow control
07 flow control
 
operators and control statements in c language
operators and control statements in c languageoperators and control statements in c language
operators and control statements in c language
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in c
 
Control structures in C
Control structures in CControl structures in C
Control structures in C
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Chapter 4.4
Chapter 4.4Chapter 4.4
Chapter 4.4
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
C programming
C programmingC programming
C programming
 

Similar to Exception Handling in .NET F# - Try/With, Raising, Finally (39

Similar to Exception Handling in .NET F# - Try/With, Raising, Finally (39 (20)

12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling.pdf
Exception Handling.pdfException Handling.pdf
Exception Handling.pdf
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Introduction to Exception
Introduction to ExceptionIntroduction to Exception
Introduction to Exception
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Java unit3
Java unit3Java unit3
Java unit3
 

More from DrRajeshreeKhande

More from DrRajeshreeKhande (20)

.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading
 
.NET F# Events
.NET F# Events.NET F# Events
.NET F# Events
 
.NET F# Class constructor
.NET F# Class constructor.NET F# Class constructor
.NET F# Class constructor
 
.NET F# Abstract class interface
.NET F# Abstract class interface.NET F# Abstract class interface
.NET F# Abstract class interface
 
.Net F# Generic class
.Net F# Generic class.Net F# Generic class
.Net F# Generic class
 
F# Console class
F# Console classF# Console class
F# Console class
 
.net F# mutable dictionay
.net F# mutable dictionay.net F# mutable dictionay
.net F# mutable dictionay
 
F sharp lists & dictionary
F sharp   lists &  dictionaryF sharp   lists &  dictionary
F sharp lists & dictionary
 
F# array searching
F#  array searchingF#  array searching
F# array searching
 
Net (f#) array
Net (f#)  arrayNet (f#)  array
Net (f#) array
 
.Net (F # ) Records, lists
.Net (F # ) Records, lists.Net (F # ) Records, lists
.Net (F # ) Records, lists
 
MS Office for Beginners
MS Office for BeginnersMS Office for Beginners
MS Office for Beginners
 
Java Multi-threading programming
Java Multi-threading programmingJava Multi-threading programming
Java Multi-threading programming
 
Java String class
Java String classJava String class
Java String class
 
JAVA AWT components
JAVA AWT componentsJAVA AWT components
JAVA AWT components
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
 
Dr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive inputDr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive input
 
Dr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to javaDr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to java
 
Java Exceptions Handling
Java Exceptions Handling Java Exceptions Handling
Java Exceptions Handling
 
Dr. Rajeshree Khande : Java Basics
Dr. Rajeshree Khande  : Java BasicsDr. Rajeshree Khande  : Java Basics
Dr. Rajeshree Khande : Java Basics
 

Recently uploaded

Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Recently uploaded (20)

Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 

Exception Handling in .NET F# - Try/With, Raising, Finally (39

  • 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
  • 13. Example  Demonstration of try…with and raise exception
  • 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
  • 17. Example invalidArg The invalidArg function generates 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
  • 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);