Java Exception Handling (Try-catch)

Sort by

recency

|

343 Discussions

|

  • + 0 comments

    public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        try{
                // Here we take input in try block, to check is  InputMismatchException occur and show it in output.
    
            int x = sc.nextInt();
            int y= sc.nextInt();
            System.out.println(x/y);
        }
        catch(InputMismatchException e){
            System.out.println("java.util.InputMismatchException");
        }
        catch(Exception e){
            System.out.println(e);
        }
    

    } }

  • + 0 comments

    By catching specific exceptions, developers can provide meaningful error messages and take corrective actions, making applications more reliable and user-friendly. Betting Exchange ID

  • + 0 comments

    public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    
        Scanner scn = new Scanner(System.in);       
        try{
            int x = scn.nextInt();
            int y = scn.nextInt();
            if(y==0)
                {
                    System.out.println("java.lang.ArithmeticException: / by zero");
                    return;
                }
            System.out.print(x/y);
        }
        catch(Exception e)
        {
            System.out.println("java.util.InputMismatchException"); 
        }       
    
    }
    

    }

  • + 0 comments
    public class Solution {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            
            try {
                int x = sc.nextInt(), y = sc.nextInt(); 
                System.out.println(x / y); 
            } catch(InputMismatchException exc) {
                System.out.println(exc.getClass().getName());
            } catch(ArithmeticException exc) {
                System.out.println(exc.getClass().getName() + ": " + exc.getMessage());
            }
            finally {
                sc.close();
            }
            
        }
    }
    
  • + 0 comments

    import java.io.; import java.util.; import java.text.; import java.math.; import java.util.regex.*;

    public class Solution {

    public static void main(String[] args) {
         try (Scanner scanner = new Scanner(System.in)) {
            int x = scanner.nextInt();
            int y = scanner.nextInt();
    
            System.out.println(x/y);
        } catch (Exception e) {
            System.out.println(getText(e));
        }
    }
    
    private static String getText(Exception e) {
        return e.toString().contains(": For input") ? e.toString().substring(0, e.toString().indexOf(":")) : e.toString();
    }
    

    }