Chapter 6 Exceptions in Java

Catalog

1. Java Exception Concepts

2. Abnormal System

3. Exception handling

4. throws

5. Custom Exceptions

1. Java Exception Concepts

Exceptions: Abnormalities that occur at run time and can be handled using exception handling mechanisms

Generalized exceptions: any abnormal error in the program

There are two categories: error: once a program runs with an error, it cannot be resolved

Exception: An abnormal condition occurs when a program is running, but it can be resolved by an exception mechanism

Narrow exception: An exception that occurs when a program is running and can be handled using an exception handling mechanism

public class ErrorDemo1 {
    public static void main(String[] args) {
        /*ErrorDemo1 errorDemo1 = new ErrorDemo1();
        errorDemo1.sum(10);*/
        /*General runtime exceptions can be handled. The default way of handling virtual machines is to stop running. The exceptions that occur explain the type of exceptions, the reason for them, and the location of the exceptions.*/
        /*NullPointerException Null pointer exception*/
        /*String s = null;
        System.out.println(s.length());*/
        /*ArrayIndexOutOfBoundsException:Array subscript out of bounds exception, indicating that the array is therefore greater than or equal to the length of the array*/
        int [] a = new int[5];
        a[5]=8;
        /*Mathematical operation exception: ArithmeticException*/
        /*int g = 10;
        int h = 0;
        System.out.println(g/h);*/
        /*Type conversion exception: ClassCastException*/
        /*Object s = "abc";
        Integer i1 = (Integer)s;
        System.out.println(i1);*/
    }
    /*Case of error: Recursive call, too many, not enough stack memory, this error will occur, StackOverflowError, indicating that memory is not enough, the program cannot run, we cannot solve it*/
    /*public int sum(int num){
        return num+sum(num-1);*/
   // }
}
​

2. Abnormal System

Categorization of exceptions: Compile-time exceptions: Must be handled during compilation, forced prompt for handling when writing code, throws/try catch  

Runtime exceptions: You can write code without processing, inherit RuntimeException, and write code without prompting for processing

 

 

3. Exception handling

There are two ways, the first is to declare exceptions, and the second is to add try{}catch(){} to places where exceptions may occur.

public class BianyiDemo {
    /*public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "abc";
        byte [] b = s.getBytes("UTF-8");
    }*/
    public static void main(String[] args) {
        String s = "abc";
        try {
            byte [] b = s.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
/*When there are multiple catch es, exceptions of the parent type need to be placed at the bottom*/
try{
     Write code with possible exceptions
 }catch( exception type parameter){
     Catch and handle exceptions of corresponding types in try
}
/* An exception occurred but was not handled. The program cannot run backwards, but the code in finally can execute*/
try{
     Write code with possible exceptions
 }catch( exception type parameter){
     Catch and handle exceptions of corresponding types in try
}finally{
     Code that must eventually be executed
}
try{
     Write code with possible exceptions
}finally{
     Code that must eventually be executed
}

Cases without finality:

public class DealDemo {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        try {
            int c = a/b;
        }catch (ArithmeticException e){
            System.out.println("Operational exception");
        }
        System.out.println("Execute the following block of code");
    }
}

The case of Ga finally:

public class FinallyDemo {
    public static void main(String[] args) {
    int a = 10;
    int b = 0;
        try {
        int c = a/b;
    }catch (ArithmeticException e){
        e.printStackTrace();
    }finally {
            System.out.println("Code block that must be executed");
        }
    }
}

4. throws

Declare that there may be exceptions to this method, throw exceptions at the declaration of the method and do not handle them, emphasizing handling during compilation

Simulations are a bottom-level method that generally does not try{}catch(){}, and continuing to declare that there may be exceptions to this method as a declaration (definition) of the method

throws+UnsupportEncodingException (compile-time exception)

Where method calls are prompted, they are handled during compilation

throws+NullpointerException (runtime exception)

Do not display prompt processing during compilation

public class ThrowsDemo {
    public static void main(String[] args) {
        try {
            ThrowsDemo.test1();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    public static void test1() throws UnsupportedEncodingException {
        ThrowsDemo.test2();
    }
    public static void test2() throws UnsupportedEncodingException {
        System.out.println("Format Correct");
    }
}

Method override: method names are the same, return values are the same, parameter lists are the same

Access equal to or greater than what the parent class declares

The declared exception type is equal to or less than the exception type declared by the parent class

public abstract class P {
    public abstract void run() throws UnsupportedEncodingException ;
    public abstract void eat() throws NullPointerException;
    public abstract void sleep() throws IOException;
}
public class S extends P {
    @Override
    public void run() throws UnsupportedEncodingException {
    }
    @Override
    public void eat() throws NullPointerException {
    }
    @Override
    /*public void sleep() throws IOException {
    }*/
    public void sleep() throws UnsupportedEncodingException {
    }
}

5. throw

Throw an exception directly, an object that throws an exception class as shown in the method, indicating that an exception actually occurred here

new + parameterized construction method (describes the cause of the exception)

e.printStackTrace(); Print exception information in console

public class ThrowDemo {
    public static void main(String[] args) {
        try {
            ThrowDemo.judge(101);
        } catch (UnsupportedEncodingException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    public static void judge(int score) throws UnsupportedEncodingException {
        if (score<0 || score > 100) {
           throw new UnsupportedEncodingException("Illegal Score");
        }else if (score >= 90){
            System.out.println("A");
        }else{
            System.out.println("B");
        }
    }
}

5. Custom Exceptions

During business development, we can develop an exception class to represent a certain kind of problem according to the actual business requirements.

public class ScoreException extends Exception{
   /*An object of this type whose score is not valid is thrown, such as a percentage test that passes in a score less than 0 or greater than 100 */
        public ScoreException() {
            super();
        }
        public ScoreException(String message) {
            super(message);
        }
}
public class Test {
    public static void main(String[] args) {
        try {
            trans(101);
        } catch (ScoreException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
    public static  String trans(int socre) throws ScoreException {
        if(socre<0||socre>100){
            throw new ScoreException("Illegal Score");
        }
        if(socre>=90){
            return "A";
        }else{
            return "B";
        }
    }
}

Tags: Java

Posted on Sun, 28 Nov 2021 23:55:17 -0500 by Grego