fromStringOrThrow

Summary

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

Usage

public static unsigned int fromStringOrThrow(string numberAsStr)

Returns

The unsigned int equivalent of the string value if the string is a valid unsigned int value and does not overflow (the string value fits within the unsigned int data range).

Parameters

numberAsStr

The string value to convert.

Description

Converts a string to a valid unsigned int value or throws an exception if the value cannot be converted. If the string value is not numeric, System.Exceptions.InvalidNumberException will be thrown. If the string value is outside the range of valid values for the unsigned int data type, System.Exceptions.IntegerOutOfRangeException is thrown.

For string values that are not numeric, System.Exceptions.InvalidNumberException is thrown:

import System;
import System.Exceptions;

try {
    unsigned int x = UInteger32.fromStringOrThrow("100");
}
catch(InvalidNumberException e) {
    // Will not execute because the string value is numeric
    Console.error(e);
}

try {
    unsigned int y = UInteger32.fromStringOrThrow("abc");
}
catch(InvalidNumberException e) {
    Console.error(e);
}

If the string being converted is numeric but does not fit into the unsigned int data range [ 0, 4294967295 ] (inclusive), System.Exceptions.IntegerOutOfRangeException will be thrown.

import System;
import System.Exceptions;

try {
    unsigned int exceedByOne = UInteger32.fromStringOrThrow("4294967296");
}
catch(IntegerOutOfRangeException e) {
    Console.error(e);
}

Examples

Valid Conversion (No exception)
1
2
3
4
5
import System;
import System.Exceptions;
 
unsigned int valid = UInteger32.fromStringOrThrow("123");
Console.log(valid); // 123
Invalid Conversion (Not numeric)
1
2
3
4
5
6
7
8
import System;
 
try {
    unsigned int invalid = UInteger32.fromStringOrThrow("abc");
}
catch(InvalidNumberException e) {
    Console.error(e);
}
Invalid Conversion (Out of range)
1
2
3
4
5
6
7
8
9
import System;
import System.Exceptions;
 
try {
    unsigned int exceedByOne = UInteger32.fromStringOrThrow("4294967296");
}
catch(IntegerOutOfRangeException e) {
    Console.error(e);
}

Share

HTML | BBCode | Direct Link