Exceptions and how to handle them

1, Exception ---- an event that causes the normal flow of a program to be interrupted, which is called an exception

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;(FileNotFoundException is a subclass of Exception)

printStackTrace --- path

2, Handling method -- try , catch , finally , throws

1,try catch

Put the code that may throw FileNotFoundException without exception in try
If the file exists, it is executed sequentially down and the code in the catch block is not executed
If the file does not exist, the code in try will terminate immediately and the program flow will run into the corresponding catch block
 e.printStackTrace(); The method call trace will be printed

2. Multiple exception capture methods ---- one exception corresponds to one catch

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class TestException {
 
    public static void main(String[] args) {
 
        File f = new File("d:/LOL.exe");
 
        try {
            System.out.println("Trying to open d:/LOL.exe");
            new FileInputStream(f);
            System.out.println("Successfully opened");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date d = sdf.parse("2016-06-03");
        } catch (FileNotFoundException e) {
            System.out.println("d:/LOL.exe non-existent");
            e.printStackTrace();
        } catch (ParseException e) {
            System.out.println("Date format parsing error");
            e.printStackTrace();
        }
    }
}

Multiple exception capture methods - exceptions are placed in one catch

File f = new File("d:/LOL.exe");
 
        try {
            System.out.println("Trying to open d:/LOL.exe");
            new FileInputStream(f);
            System.out.println("Successfully opened");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date d = sdf.parse("2016-06-03");
        } catch (FileNotFoundException | ParseException e) {
            if (e instanceof FileNotFoundException)
                System.out.println("d:/LOL.exe non-existent");
            if (e instanceof ParseException)
                System.out.println("Date format parsing error");
 
            e.printStackTrace();
        }

3. Finally --- the code in finally will be executed regardless of whether an exception occurs

  finally{
            System.out.println("Code that executes regardless of whether the file exists or not");

4. throws and throw
throws appears on the method declaration, and throw usually appears in the method body.
throws indicates a possibility of exceptions, which do not necessarily occur; Throw means that an exception is thrown, and the execution of throw must throw an exception object.

Usage:

Main method call method1
method1 calls method2
Open file in method2

Dispel doubts:

Exception handling is required in method2
However, method2 does not intend to handle it, but throws the exception through throws
Then method1 will receive the exception. There are two ways to handle it, either try catch or throw it out.
Method1 selects the local try catch. Once the try catch is stopped, it is equivalent to digesting the exception. When the main method calls method1, there is no need to handle the exception

public class TestException {
public static void main (String[]args){
   method1();
}
private static void method1{
   try{
       method2();}catch(FileNotFoundException e){
    e.printStackTrace();}
private static void method2 throws FileNotFoundException{
    File f = new File("d:/LOL.exe");
 
    System.out.println("Trying to open d:/LOL.exe");
    new FileInputStream(f);
    System.out.println("Successfully opened")
  }
 }
}

3, Exception classification ----- there are 3 types of checked exceptions, runtime exceptions (also known as non checked exceptions) and errors

1. CheckedException -- exceptions that must be handled, either try catch or throws

For example, FileNotFoundException

2. Runtime exception -- it is not an exception that must be tried catch. It will not be processed or compiled

Common runtime exceptions:
Divisor cannot be 0 exception: ArithmeticException
Subscript out of bounds exception: ArrayIndexOutOfBoundsException
Null pointer exception: NullPointerException

//Any divisor cannot be 0:ArithmeticException
        int k = 5/0;
         
//Subscript out of bounds exception: ArrayIndexOutOfBoundsException
        int j[] = new int[5];
        j[10] = 10;
         
//Null pointer exception: NullPointerException
        String str = null;
        str.length();

3. Error - system level exception, which does not require forced capture

4, Throwable class ---- Exception and Error inherit this class. It can be understood as a parent class and can also be used to catch exceptions

 

5, Exercise - account overdraft exception

This is a class diagram
Account Category: bank account number
 Properties: balance balance
 method: getBalance() Get balance
 method: deposit() save money
 method: withdraw() Withdraw money
OverdraftException:  Overdraft exception, inheritance Exception
 Properties: deficit Overdraft amount


public class Account {
    protected double balance;
    public Account(double balance){
    	this.balance=balance;\\I opened an account
    }
    public double getBalance(){
    	return balance;//Get balance
    }
    public void deposit(double amt){
    	this.balance+=amt;
    }
    public void withdraw(double amt) throws OverDraftException{
    	if(this.balance<amt)
    		throw new OverDraftException("Sorry, your credit is running low",amt-this.balance);
    
    	this.balance-=amt;
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
     Account a=new Account(10000);
     a.deposit(10000);
     System.out.println("Balance:"+a.getBalance());
     try{
    	 a.withdraw(30000);
     }catch( OverDraftException e){
    	 System.out.println("The overdraft amount is:"+e.getDecit());
    	 e.printStackTrace();
     }
	}
}


\\OverDraftException part
package yclx;

public class OverDraftException extends Exception{
    private double deficit;
    public double getDecit(){
    	return deficit;
    }
    public  OverDraftException(String msg,double deficit){
    	super(msg);
    	this.deficit=deficit;
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
    
	}

}

Added by swathin2 on Thu, 20 Jan 2022 06:40:38 +0200