Day 16: Exceptions - String to Integer

Sort by

recency

|

994 Discussions

|

  • + 0 comments

    🐍 If your try: except code can't get validation - try to delete 'if name == 'main':'

    Probably this if statement triggers an error message reading it as part of "if (...) else") statement.

    Graditudes:

    https://www.hackerrank.com/karinaxfarias https://www.hackerrank.com/przemyslaw_siek1

  • + 0 comments
    s=input()
    try:
        s=int(s)
        print(s)
    except ValueError: 
        print("Bad String")
    
  • + 1 comment

    I made a code in python using try and except, however this error is appearing in the submition "Error reading result file.You should use exception handling concepts." if name == 'main': S = input() try: integer=int(S) print(str(integer)) except ValueError: print("Bad String") pass except Exception: print("Bad String")

        pass
    
  • + 0 comments

    Solution in JavaScript/TypeScript

    In JavaScript/TypeScript, the situation is a bit different. The parseInt function does not throw an exception when the conversion fails. Instead, it returns NaN (Not-a-Number), which means we need additional validation to handle this case. Due to the challenge's restrictions, which do not allow the use of conditionals, it was not possible to submit a solution that met all the requirements. Here is an attempt at a solution in TypeScript using parseInt for conversion, but it requires additional validation for NaN:

    function throwBadString(): never {
        throw new Error("Bad String");
    }   
    
    function main() {
        const S: string = readLine();
        
        try {
            const num = parseInt(S);
            isNaN(num) && throwBadString();
            console.log(num);
        } catch (error) {
            console.log("Bad String");
        }
    }
    

    Solution in Java

    In Java, the solution was straightforward thanks to Integer.parseInt, which throws a NumberFormatException if the string cannot be converted to an integer. This allows us to handle the conversion error clearly and simply using a try-catch block. Here's the code:

    public class Solution {
        public static void main(String[] args) throws IOException {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    
            String S = bufferedReader.readLine();
            
            try {
                int result = Integer.parseInt(S);
                System.out.println(result);
            } catch (NumberFormatException e) {
                System.out.println("Bad String");
            }
    
            bufferedReader.close();
        }
    }
    
  • + 1 comment

    Hi Can someone explain why this makes the test to fail (while the output is ok..) ? Thanks in advance

    'use strict';
    
    process.stdin.resume();
    process.stdin.setEncoding('utf-8');
    
    let inputString = '';
    let currentLine = 0;
    
    process.stdin.on('data', function(inputStdin) {
        inputString += inputStdin;
    });
    
    process.stdin.on('end', function() {
        inputString = inputString.split('\n');
    
        main();
    });
    
    function readLine() {
        return inputString[currentLine++];
    }
    
    
    
    function main() {
        const S = readLine();
        
         try {
            const parsed = parseInt(S, 10)
            if (!/^\d+$/.test(S) || isNaN(parsed)) {
                throw new Error("Bad String");
            }
            console.log(parsed);
        } catch (err) {
            console.log("Bad String");
        }
    }