Home > Software engineering >  How to use Error handling / Exception Handling in Java?
How to use Error handling / Exception Handling in Java?

Time:04-27

So I'm trying to implement error catcher in my program but I'm not 100% sure on how they actually work, I have look some tutorials on YouTube but the way they explain it to me was not 100% clear, So what I'm actually trying to do here is trying to have at the end of the code something that if you insert a letter or number that he cannot recognise he's not going to give us an error but he's going to give us a message that tells us what went wrong.

What I tried to make was a much easier version with if statements, but I think that that is not exactly a good fit for this code because I would have to rewrite everything with if statements and I'm not sure how actually work.

Code that I think can work

It was not letting me put the code here :C

Code That I'm trying to implement Error handling

import java.util.Scanner;

public class main {

public static void main(String[] args) {
    
    Scanner sc= new Scanner(System.in);
       System.out.println("Insert number of students: ");
                String student = sc.nextLine();
                int studenti = Integer.parseInt(student);
                 int[] array = new int[studenti];
                for (int i = 0; i<studenti;i  )
                {
                    System.out.println("Insert a score in percentage: ");
                    String score = sc.nextLine();
                    
                    array[i]= Integer.parseInt(score);
                    
                }
                
                System.out.println("\nPercentages are: ");
                int sum = 0; // Added a variable for sum
                for (int i = 0; i < studenti; i  ) {
                  System.out.println((array[i])   "%");
                  sum  = array[i]; // maintaining sum
                }
                int average = sum / array.length; // calculating the average
                System.out.println("\nThe Average Score is: "   average   "%");

CodePudding user response:

Using a try/catch block.

    public static void main(String[] args) {
    
    Scanner sc= new Scanner(System.in);
       System.out.println("Insert number of students: ");
                String student = sc.nextLine();
          try{   
                int studenti = Integer.parseInt(student);
                 int[] array = new int[studenti];
                for (int i = 0; i<studenti;i  )
                {
                    System.out.println("Insert a score in percentage: ");
                    String score = sc.nextLine();
                    
                    array[i]= Integer.parseInt(score);
                    
                }
                
                System.out.println("\nPercentages are: ");
                int sum = 0; // Added a variable for sum
                for (int i = 0; i < studenti; i  ) {
                  System.out.println((array[i])   "%");
                  sum  = array[i]; // maintaining sum
                }
                int average = sum / array.length; // calculating the average
                System.out.println("\nThe Average Score is: "   average   "%");
    }catch(Exception ex){
     System.out.println("Error, details: "   ex.Message());
}

There are many 'Exception' you can use, numberFormatException for example.

CodePudding user response:

Error handling is not so complicated, really. It's about knowing what kind of exception is thrown in the scope of the try statement. This information is usually available by your IDE when you put the cursor over the method you are using.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    try {
        System.out.println("Insert number of students: ");
        int student = sc.nextInt(); // note Im using a method specific for int, instead of parsing
        int[] array = new int[student];
        for (int i = 0; i < student; i  ) {
            System.out.println("Insert a score in percentage: ");
            String score = sc.nextLine();
            array[i]= Integer.parseInt(score);
        }
        System.out.println("\nPercentages are: ");
        int sum = 0;
        for (int i = 0; i < student; i  ) {
            System.out.println((array[i])   "%");
            sum  = array[i];
        }
        int average = sum / student; // student == array.length
        System.out.println("\nThe Average Score is: "   average   "%");
    } catch (InputMismatchException | NumberFormatException exception) {  
        // This will catch errors due wrong input (ie user entered a letter 
        // instead of a digit) and execute the code within this block.
        // Another possible Exception thrown is IllegalStateException.
        System.err.println("There was an error. Details:");
        exception.printStackTrace(System.err); // remove if you don't want to see the error trace
    } finally { // this will get executed whether your code had errors or not
        sc.close(); // dont forget to close your scanner
    }
}

If your IDE doesn't show you information about a method, it might not be documented or you don't have said documentation imported. For that case, just google a bit and you'll find the exceptions. For example, this link show you information about Scanner.nextInt() and this about Integer.parseInt().

CodePudding user response:

The broken part in the code is divide by zero. To handle the exception

 try {
        int average = sum / array.length; // throw Exception
    }
    catch (ArithmeticException e) {
        System.out.println(
            "Divided by zero operation cannot possible");
    }
  •  Tags:  
  • java
  • Related