fromStringOrThrow

Summary

Converts a string to a valid bool value or throws an exception if the value cannot be converted.

Usage

public static bool fromStringOrThrow(string boolAsStr)

Returns

The bool equivalent of the string value if the string is a valid bool value.

Parameters

boolAsStr

The string value to convert.

Description

Converts a string to a valid bool value or throws an exception if the value cannot be converted. If the string value is not a Boolean true or false value, System.Exceptions.InvalidBooleanException will be thrown.

For string values that are not Boolean (true or false), System.Exceptions.InvalidBooleanException is thrown:

import System;
import System.Exceptions;

try {
    bool x = Boolean.fromStringOrThrow("true");
}
catch(InvalidBooleanException e) {
    // Will not execute because the string value is a valid Boolean
    Console.error(e);
}

try {
    bool y = Boolean.fromStringOrThrow("abc");
}
catch(InvalidBooleanException e) {
    Console.error(e);
}

Examples

Valid Conversion (No exception)
1
2
3
4
5
6
7
import System;
import System.Exceptions;
 
bool valid1 = Boolean.fromStringOrThrow("true");
Console.log(valid1); // true
bool valid2 = Boolean.fromStringOrThrow("false");
Console.log(valid2); // false
Invalid Conversion (Throws exceptions)
1
2
3
4
5
6
7
8
import System;
 
try {
    bool invalid = Boolean.fromStringOrThrow("abc");
}
catch(InvalidBooleanException e) {
    Console.error(e);
}

Share

HTML | BBCode | Direct Link