Thanks to visit codestin.com
Credit goes to github.com

Skip to content

System.Exception F# snippets #7725

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions snippets/fsharp/System/Exception/.ctor/fs.fsproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net48</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Compile Include="new.fs" />
<Compile Include="news.fs" />
<Compile Include="getobjdata.fs" />
<Compile Include="newsi.fs" />
</ItemGroup>

<ItemGroup>
<Reference Include="System.Runtime.Serialization.Formatters.Soap" />
</ItemGroup>
</Project>
104 changes: 104 additions & 0 deletions snippets/fsharp/System/Exception/.ctor/getobjdata.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
module NDP_UE_FS_3

//<Snippet1>
open System
open System.IO
open System.Runtime.Serialization
open System.Runtime.Serialization.Formatters.Soap
open System.Security.Permissions

// Define a serializable derived exception class.
[<Serializable>]
type SecondLevelException =
inherit Exception

interface ISerializable with
// GetObjectData performs a custom serialization.
[<SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter=true)>]
member this.GetObjectData(info: SerializationInfo, context: StreamingContext) =
// Change the case of two properties, and then use the
// method of the base class.
this.HelpLink <- this.HelpLink.ToLower()
this.Source <- this.Source.ToUpperInvariant()

base.GetObjectData( info, context )
// This public constructor is used by class instantiators.
new (message: string, inner: Exception) as this =
{ inherit Exception(message, inner) }
then
this.HelpLink <- "http://MSDN.Microsoft.com"
this.Source <- "Exception_Class_Samples"

// This protected constructor is used for deserialization.
new (info: SerializationInfo, context: StreamingContext) =
{ inherit Exception(info, context) }

printfn
"""This example of the Exception constructor and Exception.GetObjectData
with SerializationInfo and StreamingContext parameters generates
the following output.
"""

try
// This code forces a division by 0 and catches the
// resulting exception.
try
let zero = 0
let ecks = 1 / zero
()
with ex ->
// Create a new exception to throw again.
let newExcept = SecondLevelException("Forced a division by 0 and threw another exception.", ex)

printfn "Forced a division by 0, caught the resulting exception, \nand created a derived exception:\n"
printfn $"HelpLink: {newExcept.HelpLink}"
printfn $"Source: {newExcept.Source}"

// This FileStream is used for the serialization.
use stream = new FileStream("NewException.dat", FileMode.Create)

try
// Serialize the derived exception.
let formatter = SoapFormatter(null, StreamingContext StreamingContextStates.File)
formatter.Serialize(stream, newExcept)

// Rewind the stream and deserialize the
// exception.
stream.Position <- 0L
let deserExcept = formatter.Deserialize stream :?> SecondLevelException

printfn
"""
Serialized the exception, and then deserialized the resulting stream into a
new exception. The deserialization changed the case of certain properties:
"""

// Throw the deserialized exception again.
raise deserExcept
with :? SerializationException as se ->
printfn $"Failed to serialize: {se}"

with ex ->
printfn $"HelpLink: {ex.HelpLink}"
printfn $"Source: {ex.Source}"
printfn $"\n{ex}"

// This example displays the following output.
// Forced a division by 0, caught the resulting exception,
// and created a derived exception:
//
// HelpLink: http://MSDN.Microsoft.com
// Source: Exception_Class_Samples
//
// Serialized the exception, and then deserialized the resulting stream into a
// new exception. The deserialization changed the case of certain properties:
//
// HelpLink: http://msdn.microsoft.com
// Source: EXCEPTION_CLASS_SAMPLES
//
// NDP_UE_FS_3+SecondLevelException: Forced a division by 0 and threw another except
// ion. ---> System.DivideByZeroException: Attempted to divide by zero.
// at <StartupCode$fs>.$NDP_UE_FS_3.main@()
// --- End of inner exception stack trace ---
// at <StartupCode$fs>.$NDP_UE_FS_3.main@()
//</Snippet1>
68 changes: 68 additions & 0 deletions snippets/fsharp/System/Exception/.ctor/new.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
module NDP_UE_FS

//<Snippet1>
// Example for the Exception() constructor.
open System

// Derive an exception with a predefined message.
type NotEvenException() =
inherit Exception "The argument to a function requiring even input is not divisible by 2."

// half throws a base exception if the input is not even.
let half input =
if input % 2 <> 0 then
raise (Exception())
else input / 2

// half2 throws a derived exception if the input is not even.
let half2 input =
if input % 2 <> 0 then
raise (NotEvenException())
else input / 2

// calcHalf calls Half and catches any thrown exceptions.
let calcHalf input =
try
let halfInput = half input
printfn $"Half of {input} is {halfInput}."
with ex ->
printfn $"{ex}"

// calcHalf2 calls Half2 and catches any thrown exceptions.
let calcHalf2 input =
try
let halfInput = half2 input
printfn $"Half of {input} is {halfInput}."
with ex ->
printfn $"{ex}"

printfn "This example of the Exception() constructor generates the following output."
printfn "\nHere, an exception is thrown using the \nparameterless constructor of the base class.\n"

calcHalf 12
calcHalf 15

printfn "\nHere, an exception is thrown using the \nparameterless constructor of a derived class.\n"

calcHalf2 24
calcHalf2 27


// This example of the Exception() constructor generates the following output.
// Here, an exception is thrown using the
// parameterless constructor of the base class.
//
// Half of 12 is 6.
// System.Exception: Exception of type 'System.Exception' was thrown.
// at NDP_UE_FS.half(Int32 input)
// at at NDP_UE_FS.calcHalf(Int32 input)
//
// Here, an exception is thrown using the
// parameterless constructor of a derived class.
//
// Half of 24 is 12.
// NDP_UE_FS+NotEvenException: The argument to a function requiring even input is
// not divisible by 2.
// at NDP_UE_FS.half2(Int32 input)
// at NDP_UE_FS.calcHalf2(Int32 input)
//</Snippet1>
74 changes: 74 additions & 0 deletions snippets/fsharp/System/Exception/.ctor/news.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
module NDP_UE_FS_2

//<Snippet2>
// Example for the Exception(string) constructor.
open System

let notEvenMessage = "The argument to a function requiring even input is not divisible by 2."

// Derive an exception with a specifiable message.
type NotEvenException =
inherit Exception
new () = { inherit Exception(notEvenMessage) }
new (auxMessage) = { inherit Exception($"{auxMessage} - {notEvenMessage}") }

// half throws a base exception if the input is not even.
let half input =
if input % 2 <> 0 then
raise (Exception $"The argument {input} is not divisible by 2.")
else input / 2

// half2 throws a derived exception if the input is not even.
let half2 input =
if input % 2 <> 0 then
raise (NotEvenException $"Invalid argument: {input}")
else input / 2

// calcHalf calls Half and catches any thrown exceptions.
let calcHalf input =
try
let halfInput = half input
printfn $"Half of {input} is {halfInput}."
with ex ->
printfn $"{ex}"

// calcHalf2 calls Half2 and catches any thrown exceptions.
let calcHalf2 input =
try
let halfInput = half2 input
printfn $"Half of {input} is {halfInput}."
with ex ->
printfn $"{ex}"

printfn "This example of the Exception(string)\nconstructor generates the following output."
printfn "\nHere, an exception is thrown using the \nconstructor of the base class.\n"

calcHalf 18
calcHalf 21

printfn "\nHere, an exception is thrown using the \nconstructor of a derived class.\n"

calcHalf2 30
calcHalf2 33


// This example of the Exception(string)
// constructor generates the following output.
//
// Here, an exception is thrown using the
// constructor of the base class.
//
// Half of 18 is 9.
// System.Exception: The argument 21 is not divisible by 2.
// at NDP_UE_FS_2.half(Int32 input)
// at NDP_UE_FS_2.calcHalf(Int32 input)
//
// Here, an exception is thrown using the
// constructor of a derived class.
//
// Half of 30 is 15.
// NDP_UE_FS_2+NotEvenException: Invalid argument: 33 - The argument to a function r
// equiring even input is not divisible by 2.
// at NDP_UE_FS_2.half2(Int32 input)
// at NDP_UE_FS_2.calcHalf2(Int32 input)
//</Snippet2>
60 changes: 60 additions & 0 deletions snippets/fsharp/System/Exception/.ctor/newsi.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
module NDP_UE_FS_4

//<Snippet3>
// Example for the Exception(string, Exception) constructor.
open System

let overflowMessage = "The log table has overflowed."

// Derive an exception with a specifiable message and inner exception.
type LogTableOverflowException =
inherit Exception

new () = { inherit Exception(overflowMessage) }

new (auxMessage: string) =
{ inherit Exception($"{overflowMessage} - {auxMessage}") }

new (auxMessage: string, inner: Exception) =
{ inherit Exception($"{overflowMessage} - {auxMessage}", inner ) }

type LogTable(numElements: int) =
let mutable logArea = Array.zeroCreate<string> numElements
let mutable elemInUse = 0

// The AddRecord method throws a derived exception
// if the array bounds exception is caught.
member _.AddRecord(newRecord: string): int =
try
logArea[elemInUse] <- newRecord
elemInUse <- elemInUse + 1
elemInUse - 1
with ex ->
raise (LogTableOverflowException($"Record \"{newRecord}\" was not logged.", ex ) )

// Create a log table and force an overflow.
let log = LogTable 4

printfn "This example of the Exception(string, Exception)\nconstructor generates the following output."
printfn "\nExample of a derived exception that references an inner exception:\n"
try
for count = 1 to 1000 do
log.AddRecord $"Log record number {count}"
|> ignore
with ex ->
printfn $"{ex}"


// This example of the Exception(string, Exception)
// constructor generates the following output.
//
// Example of a derived exception that references an inner exception:
//
// NDP_UE_FS_4+LogTableOverflowException: The log table has overflowed. - Record "Lo
// g record number 5" was not logged. ---> System.IndexOutOfRangeException: Index
// was outside the bounds of the array.
// at NDP_UE_FS_4.LogTable.AddRecord(String newRecord)
// --- End of inner exception stack trace ---
// at NDP_UE_FS_4.LogTable.AddRecord(String newRecord)
// at <StartupCode$fs>.$NDP_UE_FS_4.main@()
//</Snippet3>
60 changes: 60 additions & 0 deletions snippets/fsharp/System/Exception/Data/data.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//<snippet1>
// This example demonstrates the Exception.Data property.
open System
open System.Collections

let nestedRoutine2 displayDetails =
let e = Exception "This statement is the original exception message."
if displayDetails then
let s = "Information from nestedRoutine2."
let i = -903
let dt = DateTime.Now
e.Data.Add("stringInfo", s)
e.Data["IntInfo"] <- i
e.Data["DateTimeInfo"] <- dt
raise e

let nestedRoutine1 displayDetails =
try
nestedRoutine2 displayDetails
with e ->
e.Data["ExtraInfo"] <- "Information from nestedRoutine1."
e.Data.Add("MoreExtraInfo", "More information from nestedRoutine1.")
reraise ()

let runTest displayDetails =
try
nestedRoutine1 displayDetails
with e ->
printfn "An exception was thrown."
printfn $"{e.Message}"
if e.Data.Count > 0 then
printfn " Extra details:"
for de in e.Data do
let de = de :?> DictionaryEntry
printfn $""" Key: {"'" + de.Key.ToString() + "'",-20} Value: {de.Value}"""

printfn "\nException with some extra information..."
runTest false
printfn "\nException with all extra information..."
runTest true


// The example displays the following output:
// Exception with some extra information...
// An exception was thrown.
// This statement is the original exception message.
// Extra details:
// Key: 'ExtraInfo' Value: Information from NestedRoutine1.
// Key: 'MoreExtraInfo' Value: More information from NestedRoutine1.
//
// Exception with all extra information...
// An exception was thrown.
// This statement is the original exception message.
// Extra details:
// Key: 'stringInfo' Value: Information from NestedRoutine2.
// Key: 'IntInfo' Value: -903
// Key: 'DateTimeInfo' Value: 7/29/2013 10:50:13 AM
// Key: 'ExtraInfo' Value: Information from NestedRoutine1.
// Key: 'MoreExtraInfo' Value: More information from NestedRoutine1.
//</snippet1>
Loading