6 Java exceptions try catch, try catch finally, try finally and throws declaration and throw throw throw

Posted by virtualdevl on Tue, 25 Jan 2022 19:33:57 +0100

abnormal

1. What is an exception?

Broadly speaking, exception refers to all abnormal conditions, including Error Exception
In java, abnormal conditions are divided into:

Error: refers to problems that cannot be solved by the program, such as insufficient memory, heap overflow and JVM crash

Exception (narrow sense): for example: stack overflow, arithmetic exception, array out of bounds, number formatting, null correction, type conversion

2. Abnormal system (Throwable)

​ java.lang**.Throwable * *: two direct subclasses Java lang.Error java. lang.Excepetion

Exception s fall into two categories:

1) Runtime Exception, which can not be handled during compilation, is judged according to experience
2) check the exception Checked Exception, which is a compile time exception and is forced to be handled when writing code

3. How to solve the exception?

For exceptions, there are generally two solutions:

  • One is to terminate the operation of the program in case of an exception.

  • Second, when programmers write, they consider the detection of exceptions, the prompt of exception messages, and the handling of exceptions

    The best way to catch exceptions is at compile time, but some exceptions only occur at run time.

    Classification: compile time exception, run-time exception

When writing code, predict the possible problems in the program and capture and deal with the problems
The program is executed normally. If there is no problem, follow the normal process. If there is an exception, follow the pre-defined processing process.

try{

   //Possible exception codes

}catch( Exception type  a){

    //Handle the corresponding type of exception

}
try{

      //Possible exception codes

}catch( Exception type  a){
		
		//Handle the corresponding type of exception
    	//There can be multiple catch es 

}finally{
		
      //Write the logic that must be executed to the finally code block
      //The content of this code block is bound to execute even if an exception occurs
      //There can only be one finally
}
try{
  

}finally{
	
    
} 
//If an exception occurs, execute the logic that must be executed

Exception handling Keywords: 5 try, catch, finally, throw, throws

Error and Exception

package com.ffyc.javaexception;

public class Demo1 {
    public static void main(String[] args) {

/*
        //Error error
        int [] a = new int[Integer.MAX_VALUE];//Heap overflow
*/
        //Expecetion exception
        Demo1.test(); //Stack overflow
    }

    public  static  void test(){
        test();
    }
}
package com.ffyc.javaexception;

public class ExpecetionDemo {

    /*
    Abnormal cases
     */
    public static void main(String[] args) {

//        int a =10;
//        int b = 0 ;
//        System.out.println(a/b);   			// Arithmetic anomaly
//        System.out.println("later code");
        /* java The problems that will occur in the syntax are wrapped into a class. When such problems occur in the program, such objects are thrown

                                    Arithmeticexception:Exception type (under what syntax conditions) by zero: reason of arithmetic exception
        Exception in thread "main" java.lang.ArithmeticException: / by zero
           at com.ffyc.javaexception.ExpecetionDemo.main(ExpecetionDemo.java:12) Abnormal location

           java By default, if an exception occurs, simply and rudely throw the exception information, and then terminate the program.
         */
//        int [] a = new int[5];
//        a[5] = 10;
        /*                                       Array out of bounds
        Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
           at com.ffyc.javaexception.ExpecetionDemo.main(ExpecetionDemo.java:23)
         */

//        Object s =100 ;
//        String s1 = (String)s;
        /*                                      Class conversion exception
         Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
           at com.ffyc.javaexception.ExpecetionDemo.main(ExpecetionDemo.java:30)
         */

//        String s = null;
//        s.length();
        /*                                      Null pointer exception
        Exception in thread "main" java.lang.NullPointerException
           at com.ffyc.javaexception.ExpecetionDemo.main(ExpecetionDemo.java:37)
         */

        Integer a = new Integer("1a0");
        /*                                      Number format exception
        Exception in thread "main" java.lang.NumberFormatException: For input string: "1a0"
            at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
            at java.lang.Integer.parseInt(Integer.java:580)
            at java.lang.Integer.<init>(Integer.java:867)
            at com.ffyc.javaexception.ExpecetionDemo.main(ExpecetionDemo.java:43)

         */
    }
}

try catch

package com.ffyc.javaexception;

public class Demo3 {
    public static void main(String[] args) {

        /*
            try{
                Possible exception codes
            }catch(Specific exception type (formal parameter){
                Handling of exceptions
            }
            
            A try can correspond to multiple catches, and each catch corresponds to an exception type
            Large types of catch are written below
         */
        int a = 10;
        int b = 0 ;
        try{
            int c = a/b;

            String s = null;
            s.length();

            new Integer(a); // NumberFormatException

        }catch ( ArithmeticException ae ) { //Capture arithmetic exception
            System.out.println("Arithmetic operator");
        }catch ( NullPointerException ne ){    //Catch null pointer exception
            System.out.println("Object cannot be empty");
        }catch ( Exception e ){  //If you are not sure what else is abnormal, you can expand the range of abnormalities and polymorphism
            e.printStackTrace(); // During development, this method is used to print and output log information to the console, and later output the information to the file through the log component
            System.out.println(e.getMessage());
            System.out.println("The system is busy, please try again later!");
        }
        System.out.println("The following procedures continue to be executed");

    }
}

try catch finally

package com.ffyc.javaexception;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

public class Demo4 {

    public static void main(String[] args) {

        /*
          try catch finally
         */
        
        
/*        
		try{

            System.out.println(10/0);
            
        }catch(Exception e ){
        
            System.out.println("Program error '');
            
        }finally {
        
            System.out.println("Close connection "");

        }
        System.out.println("The following code ");
        
*/

        System.out.println( Demo4.test(10, 0));
    }

    public static int test(int a ,int b){
        try{
            int c =a/b;
            return c;
        }catch (Exception e){
            System.out.println("Program error");
            return  -1;//If an exception occurs, return - 1
        }finally {
            System.out.println("Close connection");
        }
    }//A program error occurred. Close connection - 1

}

try finally

try{

}finally{
	
    
} 
//If an exception occurs, execute the logic that must be executed

throws declaration exception

  • Declare a method, which means that this method does not handle exceptions, but is handed over to the method caller for processing

For example: public void test throws exception 1, exception 2, exception 3{

}

  • Any method can use the throws keyword to declare exception types, including abstract methods.

  • Subclasses override methods in the parent class. Subclass methods cannot declare and throw exceptions larger than the parent type (for compile time exceptions)

  • When using the throws method, you must handle the declared exception when calling, or use try -catch, and the demon will continue to use the throws declaration

package com.ffyc.javaexception;

import java.io.UnsupportedEncodingException;

public class Demo5 {

    public static void main(String[] args) {
        
        try {
            Demo5.test1();
            System.out.println("sssss");
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }

    //Generally, exceptions are not handled at the bottom, declared, thrown, and handled at the top
    public  static  void test1()throws UnsupportedEncodingException {
        System.out.println("test1");
        Demo5.test2();
    }

    /*
    throws At the declaration of the method, some exception type may occur when declaring this method
    If the thrown arithmetic exception is throws arithmeticexception, which is a runtime exception, the calling place can be handled or not

    UnsupportedEncodingException If it is a compile time exception (check exception), whoever calls this method must handle it during compilation (try catch throws)
     */
    public static  void test2() throws  ArithmeticException {
        System.out.println("test2");
        try {
            "abc".getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(10/0);
    }
}

throw throws an exception

Exception: parent class implementation exception and subclass definition

Interface: the parent class defines the interface and the child class implements it

Throw: actively throw an exception object in the program, indicating that some exception has occurred in this method

package com.ffyc.javaexception;

public class Demo7 {

    public static void main(String[] args) {

        try{
            checkScore(118);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    public  static  char checkScore(int score) throws Exception {

        if(score <0||score > 90){

            //Actively throw an exception object using the throw keyword in the program
            throw new Exception("Invalid score");
        }

        if(score >= 90){
            return  'A';
        }else{
            return 'B';
        }
    }
}

Custom exception

  • Is the self-defined exception class
  • That is, the direct or indirect subclass of the standard exception class in the API
  • Function: Mark exceptions of business logic with user-defined exceptions to avoid confusion with standard exceptions
package com.ffyc.javaexception;

public class ScoreException extends  Exception {

  /*
      Custom exception:
          It is mainly output when the business logic in the program is not satisfied
          Output such objects when the percentage system output is not satisfied
   */
      public ScoreException (String message){

          super(message);
      }

}
package com.ffyc.javaexception;

public class Demo7 {

    public static void main(String[] args) {

        try{
            checkScore(118);
        }catch (ScoreException e){
            System.out.println(e.getMessage());
        }
    }

    public  static  char checkScore(int score) throws ScoreException{

        if(score <0||score > 90){

            //Actively throw an exception object using the throw keyword in the program
            throw new ScoreException("Invalid score");
        }

        if(score >= 90){
            return  'A';
        }else{
            return 'B';
        }
    }
}

Topics: Java Back-end