JavaRush/Java Blog/Random EN/Exceptions and their handling
articles
Level 15

Exceptions and their handling

Published in the Random EN group
members
Exceptions or exceptional situations (states) are errors that occur in a program during its operation. All exceptions in Java are objects. Therefore, they can be generated not only automatically when an exceptional situation occurs, but also created by the developer himself. Hierarchy of exception classes: Exceptions and their handling - 1Exceptions are divided into several classes, but they all have a common ancestor - the class Throwable. Its descendants are the subclasses Exceptionand Error. Exceptions ( Exceptions) are the result of problems in a program that are, in principle, solvable and predictable. For example, division by zero occurred in integers. Errors ( Errors) are more serious problems that the Java specification states that you should not attempt to handle in your own program because they are JVM-level problems. For example, exceptions of this kind occur if the memory available to the virtual machine has run out. The program will still not be able to provide additional memory for the JVM. In Java, all exceptions are divided into three types: checked exceptions ( checked) and unchecked exceptions ( unchecked) which include errors ( Errors) and run-time exceptions ( RuntimeExceptionsclass descendant Exception). Controlled exceptions are errors that can and should be handled in a program; all descendants of a class Exception(but not RuntimeException) belong to this type. Exception handling can be done using operators try…catchor transferred to the external part of the program. For example, a method can pass exceptions that occur in it higher in the call hierarchy without handling it itself. Unchecked exceptions do not require handling, but you can handle class exceptions if you wish RuntimeException. Let's compile and run the following program:
class Main {
     public static void main(String[] args) {
         int a = 4;
         System.out.println(a/0);
     }
}
When launched, the following message will be displayed on the console:
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at Main.main(Main.java:4)
The message shows the class of the exception that occurred - ArithmeticException. This exception can be handled:
class Main {
     public static void main(String[] args) {
         int a = 4;
         try {
              System.out.println(a/0);
         } catch (ArithmeticException e) {
              System.out.println("Произошла недопустимая арифметическая операция");
         }
     }
}
Now, instead of a standard error message, a block will be executed catch, the parameter of which is the object e of the class corresponding to the exception (the object itself can be given any name, it will be needed if we want to forcefully throw this exception again, for example, so that it is checked some other handler). In this case, the block trycontains the fragment of the program where an exception could potentially occur. One trycan correspond to several catch blocks with different exception classes.
import java.util.Scanner;
class Main {
    public static void main(String[] args) {
     int[] m = {-1,0,1};
        Scanner sc = new Scanner(System.in);
        try {
            int a = sc.nextInt();
            m[a] = 4/a;
            System.out.println(m[a]);
        } catch (ArithmeticException e) {
            System.out.println("Произошла недопустимая арифметическая операция");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Обращение по недопустимому индексу массива");
        }
    }
}
If, after launching the presented program, the user enters from keyboard 1 or 2, the program will run without creating any exceptions. If the user enters 0, an exception of class will occur ArithmeticExceptionand will be handled by the first block catch. If the user enters 3, a class exception will occur ArrayIndexOutOfBoundsException(array out of bounds), and it will be processed by the second block catch. If the user enters a non-integer number, for example, 3.14, then a class exception will occur InputMismatchException(input type mismatch), and it will be thrown in standard error format, since we did not handle it in any way. You can, however, add a handler for the class Exception, since this class is the parent class for all other checked exceptions, it will catch any of them (including InputMismatchException).
import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        int[] m = {-1,0,1};
        int a = 1;
        Scanner sc = new Scanner(System.in);
        try {
            a = sc.nextInt();
            m[a-1] = 4/a;
            System.out.println(m[a]);
        } catch (ArithmeticException e) {
            System.out.println("Произошла недопустимая арифметическая операция");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Обращение по недопустимому индексу массива");
        } catch (Exception e) {
            System.out.println("Произошло ещё Howое-то исключение");
        }
    }
}
Since exceptions are built on a hierarchy of classes and subclasses, you should first try to handle more specific exceptions and only then more general ones. That is, if we placed the block with class exception handling first (and not third) Exception, we would never see any error messages other than “Some other exception has occurred” (all exceptions would be caught immediately by this block and would not reach the rest). An optional addition to blocks try…catchcan be a block finally. The commands placed in it will be executed in any case, regardless of whether an exception occurs or not. Despite the fact that when an unhandled exception occurs, the part of the program remaining after the generation of this exception is not executed. For example, if an exception occurred during some lengthy calculations, finallyyou can show or save intermediate results in a block. Link to source: Exceptions and their handling
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet