Day 16: Exceptions - String to Integer

Sort by

recency

|

997 Discussions

|

  • + 0 comments

    If anyone is trying to solve this problem in Python3. Then use this code not the pre-defined code:

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

    For JS this worked:

    function main() {
      const S = readLine();
      try {
        const num = JSON.parse(S);
        console.log(num);
      } catch (e) {
        console.log("Bad String");
      }
    }
    

    But for Python I get: Error reading result file.You should use exception handling concepts.

    I tried this:

        S = input()
        
        try:
            num=int(S)
            print(num)
        except ValueError: 
            print("Bad String")
    

    and this:

        S = input()
        
        try:
            num=int(S)
            print(num)
        except: 
            raise Exception("Bad String")
    

    None of these worked.

  • + 0 comments

    For JS this worked:

    function main() {
      const S = readLine();
      try {
        const num = JSON.parse(S);
        console.log(num);
      } catch (e) {
        console.log("Bad String");
      }
    }
    
    I tried this: 
    
    S = input()
    
    try:
        num=int(S)
        print(num)
    except ValueError: 
        print("Bad String")
    
    and this:
    
    S = input()
    
    try:
        num=int(S)
        print(num)
    except: 
        raise Exception("Bad String")
    

    ` None of these worked.

  • + 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")