Day 16: Exceptions - String to Integer

Sort by

recency

|

987 Discussions

|

  • + 0 comments

    Here's the ugly Typescript that doesn't use conditionals, lol.

    function fail() {
        throw new Error("Not an int")
    }
    
    function main() {
        const S: string = readLine();
        try {
            const num = Number(S)
            const test = !Number.isInteger(num) && fail()
            console.log(num)
        } catch (e) {
            console.log("Bad String")
        }
    }
    
  • + 1 comment

    I don't think you can actually complete this task using Typescript as the resulting number is just NaN and throwing your own error will fail becasue you have an if statement.

  • + 1 comment

    Hey, Here is my code : " if name == 'main': a = input() try: print(int(a)) except Exception: print('Bad String') " and the rerult is: "Error reading result file.You should use exception handling concepts."

    help me please :)

  • + 0 comments
    import math
    import os
    import random
    import re
    import sys
    
    
    S = input().strip()
    try:    
        parsed_int = int(S)
        print(parsed_int)
    except ValueError:
        print("Bad String")
    
  • + 0 comments

    import Foundation

    /* * Define an ErrorType */ enum StringToIntTypecastingError: Error { case BadString }

    func stringToInt(inputString: String) throws -> Int {
        guard let int = Int(inputString) else {
            throw StringToIntTypecastingError.BadString
        }
        return int
    }
    

    /* * Read the input */ let inputString = readLine()!

    do { try print(stringToInt(inputString: inputString)) } catch StringToIntTypecastingError.BadString { print("Bad String") }

    **// I am getting Error reading result file.You should use exception handling concepts.

    but output printing correct can any one please help in this in Swift language **