JAVA foundation [day12]: exception

Keywords: Java Interview OOP

I can't do too many things in my life, so everything should be wonderful-------- Steve Jobs

abnormal

(1) Abnormal conditions in the program.
(2) Abnormal system
Throwable
|– Error is a serious problem and we won't deal with it.
|–Exception
|– RuntimeException is a runtime exception. We need to correct the code
|– non RuntimeException compile time exception, which must be handled, otherwise the program will not compile
(3) Exception handling:
A: Default processing of JVM
Output the name, reason, location and other information of the exception on the console, but the program cannot continue to execute.
B: Handle yourself
a:try...catch...finally
Write your own processing code, and the subsequent programs can continue to execute
b:throws
Declare what you can't handle on the method and tell the caller that there is a problem
(4) Interview questions
A: What is the difference between compile time exceptions and run-time exceptions?
Compile time exceptions must be handled, otherwise the compilation fails
Run time exceptions can be handled either without or without processing
B:throw and throws are the difference
throw:
In the method body, the exception object name is followed and can only be one
throw throws an exception object, indicating that there must be an exception here
throws:
The method declaration is followed by the class name of the exception, which can be multiple
throws is a possibility that the declared method has an exception. This exception does not necessarily occur
(5)finally keyword and its interview questions
A:finally is used to release resources, and its code will always execute. Special case: the jvm exits before finally executing
B: Interview questions
a: The difference between final, finally and finalize?
b: If there is a return in catch, will finally execute it? If executed, before or after return
Yes, before.
Actually in the middle. We talked about this class

C: deformation of exception handling
​ try...catch...finally
​ try...catch...
​ try...catch...catch...
​ try...catch...catch...fianlly
​ try...finally

(6) Custom exception
Inheriting from Exception or RuntimeException, you only need to provide a parameterless construct and a parameterless construct
(7) Abnormal attention implementation
A: The parent method throws an exception, and the child override method must be less than or equal to the parent exception when throwing an exception
B: The parent method does not throw an exception, and the child override method cannot throw an exception
C: The parent method throws multiple exceptions, and the child's override method must be less or smaller than the parent method

give an example

package cn.yuan;

/*
 * Exception: an abnormal condition has occurred in the program.
 * 
 * For example: the weather is fine today. The monitor went on a trip. Ride a bike and go to the mountain for fresh air.
 * 		Question 1: the mountain road collapsed and the monitor stopped in time, but he couldn't get through it. Serious problems.
 * 		Question 2: when the monitor went out to push the bike, he found that the air was gone and blew it up. Problems that should be checked before departure.
 * 		Question 3: the monitor rode comfortably on the mountain road. There were small stones on both sides of the mountain road and a flat cement road in the middle.
 * 			There was no problem driving on the flat cement road all the time, but he liked to ride on the pebbles, so he had a flat tire. Problems in the process of tourism.
 * 			no zuo no die. 
 * 
 * Program exception: Throwable
 * 		Serious problem: we don't deal with Error. This problem is usually very serious, such as memory overflow.
 * 		Question: Exception
 * 			Compilation time problem: exceptions that are not runtimeexceptions must be handled, because if you do not handle them, the compilation cannot pass.
 * 			Runtime problem: RuntimeException 	 We don't deal with this kind of problem, because it's your problem, and the problem must be that our code is not rigorous enough and needs to be corrected.
 * 
 * We didn't deal with any problems in the application, and the jvm will eventually deal with them by default.
 * Output the name, cause and problem of the exception on the console.
 * The program will end at the same time.
 */
public class ExceptionDemo {
	public static void main(String[] args) {
		//Phase I
		int a = 10;
		// int b = 2;
		int b = 0;
		System.out.println(a / b); 
		//Phase II
		System.out.println("over");
	}
}

try...catch...finally

package cn.yuan;

/*
 * How do we handle exceptions ourselves?
 * A:try...catch...finally
 * B:throws Throw
 * 
 * try...catch...finally Processing format:
 * 		try {
 * 			Codes that may cause problems;
 * 		}catch(Exception name (variable){
 * 			Handling of problems;
 * 		}finally {
 * 			Release resources;
 * 		}
 * 
 * Deformation format:
 * 		try {
 * 			Codes that may cause problems;
 * 		}catch(Exception name (variable){
 * 			Handling of problems;
 * 		}
 * 
 * be careful:
 * 		A:try The less code inside, the better
 * 		B:catch There must be content, even if it is a simple hint
 */
public class ExceptionDemo {
	public static void main(String[] args) {
		// Phase I
		int a = 10;
		// int b = 2;
		int b = 0;

		try {
			System.out.println(a / b);
		} catch (ArithmeticException ae) {
			System.out.println("Divisor cannot be 0");
		}

		// Phase II
		System.out.println("over");
	}
} 

/*
 * A:An exception
 * B:Handling of the second exception
 * 		a:Write a try...catch for each
 * 		b:Write a try and multiple catch es
 * 			try{
 * 				...
 * 			}catch(Exception class name (variable name){
 * 				...
 * 			}
 * 			catch(Exception class name (variable name){
 * 				...
 * 			}
 * 			...
 * 
 * 			matters needing attention:
 * 				1:Be as clear as possible. Don't use big ones.
 * 				2:It doesn't matter who is in front of the exception of the horizontal relationship. If there is a child parent relationship, the parent must be behind.
 * 
 * be careful:
 * 		Once there is a problem in try, the problem will be thrown out here and matched with the problem in catch,
 * 		Once there is a match, execute the processing in catch, and then end the try...catch
 * 		Continue to execute the following statements.
 */
class ExceptionDemo2 {
	public static void main(String[] args) {
		// method1();

		// method2();

		// method3();

		method4();
	}

	public static void method4() {
		int a = 10;
		int b = 0;
		int[] arr = { 1, 2, 3 };

		// Grandpa is at the end
		try {
			System.out.println(a / b);
			System.out.println(arr[3]);
			System.out.println("There is an exception here. You don't know who it is and what to do?");
		} catch (ArithmeticException e) {
			System.out.println("Divisor cannot be 0");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("You accessed an index that should not be accessed");
		} catch (Exception e) {
			System.out.println("Something's wrong");
		}

		// Grandpa can't be in front
		// try {
		// System.out.println(a / b);
		// System.out.println(arr[3]);
		// System.out.println("there is an exception here. You don't know who it is and what to do?");
		// } catch (Exception e) {
		// System.out.println("something's wrong");
		// } catch (ArithmeticException e) {
		// System.out.println("divisor cannot be 0");
		// } catch (ArrayIndexOutOfBoundsException e) {
		// System.out.println("you accessed an index that should not be accessed");
		// }

		System.out.println("over");
	}

	// Handling of two exceptions
	public static void method3() {
		int a = 10;
		int b = 0;
		int[] arr = { 1, 2, 3 };

		try {
			System.out.println(arr[3]);
			System.out.println(a / b);
			// System.out.println(arr[3]);
		} catch (ArithmeticException e) {
			System.out.println("Divisor cannot be 0");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("You accessed an index that should not be accessed");
		}

		System.out.println("over");
	}

	// Two exceptions
	public static void method2() {
		int a = 10;
		int b = 0;
		try {
			System.out.println(a / b);
		} catch (ArithmeticException e) {
			System.out.println("Divisor cannot be 0");
		}

		int[] arr = { 1, 2, 3 };
		try {
			System.out.println(arr[3]);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("You accessed an index that should not be accessed");
		}

		System.out.println("over");
	}

	// An exception
	public static void method1() {
		// Phase I
		int a = 10;
		// int b = 2;
		int b = 0;

		try {
			System.out.println(a / b);
		} catch (ArithmeticException ae) {
			System.out.println("Divisor cannot be 0");
		}

		// Phase II
		System.out.println("over");
	}
}

The difference between compile time exceptions and runtime exceptions

package cn.yuan;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * The difference between compile time exceptions and runtime exceptions
 * Compile time exception: the Java program must display processing, otherwise the program will have an error and cannot be compiled
 * Run time exception: no display processing is required, and it can also be handled like compile time exception
 */
public class ExceptionDemo {
	public static void main(String[] args) {
		// int a = 10;
		// int b = 0;
		// if (b != 0) {
		// System.out.println(a / b);
		// }

		String s = "2014-11-20";
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// Date d = sdf.parse(s);
		try {
			Date d = sdf.parse(s);
			System.out.println(d);
		} catch (ParseException e) {
			// e.printStackTrace();
			System.out.println("There is a problem parsing the date");
		}
	}
}

Several methods in exception

package cn.yuan;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * After finding a problem in the try, the jvm will help us generate an exception object, and then throw this object to match the class in the catch.
 * If the object is of a certain type, the processing information in the catch will be executed.
 * 
 * Several methods to understand in exceptions:
 * public String getMessage():Unexpected message string		
 * public String toString():Returns a simple description of the exception
 * 		The name (full pathname) of the class of this object
 * 		": "(Colon and a space) 
 * 		The result of calling the getLocalizedMessage() method of this object (the content of getMessage() is returned by default)
 * printStackTrace() Get the exception class name, exception information, and the location of the exception in the program. The return value is void. Output the information on the console.
 */
public class ExceptionDemo {
	public static void main(String[] args) {
		String s = "2021-10-09";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date d = sdf.parse(s); // Create a ParseException object, throw it out, and match it with the catch
			System.out.println(d);
		} catch (ParseException e) { // ParseException e = new ParseException();
			// ParseException
			// e.printStackTrace();

			// getMessage()
			// System.out.println(e.getMessage());
			// Unparseable date: "2014-11-20"

			// toString()
			// System.out.println(e.toString());
			// java.text.ParseException: Unparseable date: "2014-11-20"
			
			e.printStackTrace();
			//Jump to a specified page (index.html)
		}
		
		System.out.println("over");
	}
}

throws

package cn.yuan;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * Sometimes we can handle exceptions, but sometimes we don't have permission to handle an exception at all.
 * Or if I can't handle it, I won't handle it.
 * In order to solve the error problem, Java provides another solution for this situation: throw.
 * 
 * Format:
 * 		throws Exception class name
 * 		Note: this format must follow the parentheses of the method.
 * 
 * be careful:
 * 		Try not to throw exceptions on the main method.
 * 		But I did it for my convenience.
 * 
 * Summary:
 * 		Compile time exceptions are thrown and must be handled by future callers.
 * 		The runtime exception is thrown, which can be called in the future without processing.
 */
public class ExceptionDemo {
	public static void main(String[] args) {
		System.out.println("the weather is nice today");
		try {
			method();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		System.out.println("But there should be no haze");

		method2();
	}

	// Throw of runtime exception
	public static void method2() throws ArithmeticException {
		int a = 10;
		int b = 0;
		System.out.println(a / b);
	}

	// Throw of compile time exception
	// Thrown on the method declaration to tell the caller that you have noticed that I have a problem.
	public static void method() throws ParseException {
		String s = "2014-11-20";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d = sdf.parse(s);
		System.out.println(d);
	}
}

The difference between throws and throw (interview question)

package cn.yuan;

/*
 * throw:If an exception occurs, we can throw the exception. At this time, the object thrown should be the exception object.
 * 
 * throws The difference between and throw (interview question)
	throws
		Used after the method declaration, followed by the exception class name
		It can be separated from multiple exception class names by commas
		Indicates that an exception is thrown and handled by the caller of the method
		throws Indicates a possibility of exceptions that do not necessarily occur
	throw
		Used in the method body, followed by the exception object name
		Only one exception object name can be thrown
		Indicates that an exception is thrown and handled by the statement in the method body
		throw If you execute throw, you must throw an exception
 */
public class ExceptionDemo {
	public static void main(String[] args) {
		// method();
		
		try {
			method2();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void method() {
		int a = 10;
		int b = 0;
		if (b == 0) {
			throw new ArithmeticException();
		} else {
			System.out.println(a / b);
		}
	}

	public static void method2() throws Exception {
		int a = 10;
		int b = 0;
		if (b == 0) {
			throw new Exception();
		} else {
			System.out.println(a / b);
		}
	}
}

finally

package cn.yuan;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * finally:The body of the finally controlled statement must be executed
 * Note: if the jvm exits before finally, it cannot be executed.
 * 
 * A:format
 * 		try...catch...finally...
 * B:It is used to release resources, which can be seen in IO stream operation and database operation
 */
public class FinallyDemo {
	public static void main(String[] args) {
		String s = "2014-11-20";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Date d = null;
		try {
			// System.out.println(10 / 0);
			d = sdf.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
			System.exit(0);
		} finally {
			System.out.println("The code here is executable");
		}

		System.out.println(d);
	}
}

The difference between final,finally and finalize

package cn.yuan;

/*
 * Interview questions:
 * 1:final,finally The difference between and finalize
 * final: The final meaning can modify classes, member variables and member methods
 * 		Class cannot be inherited
 * 		Modify a variable. A variable is a constant
 * 		Modifier method, method cannot be overridden
 * finally: It is part of exception handling and is used to release resources.
 * 		Generally speaking, the code is bound to execute, and the special case is that the jvm exits before finally executing
 * finalize: Is a method of the Object class for garbage collection
 * 
 * 2:If there is a return statement in catch, will the code in finally be executed?
 *   If yes, before or after return.
 * 	   meeting. front.
 * 
 * 	 To be exact, it should be in the middle.
 * 
 * 3:try...catch...finally Format deformation of
 * 		A:try...catch...finally
 * 		B:try...catch
 * 		C:try...catch...catch...
 * 		D:try...catch...catch...finally
 * 		E:try...finally
 * 			The current of this practice is to release resources.
 */
public class FinallyDemo2 {
	public static void main(String[] args) {
		System.out.println(getInt());
	}

	public static int getInt() {
		int a = 10;
		try {
			System.out.println(a / 0);
			a = 20;
		} catch (ArithmeticException e) {
			a = 30;
			return a;
			/*
			 * return a When the program reaches this step, this is not return a, but return 30; This return path is formed.
			 * However, it finds that there is finally, so continue to execute the finally content, a=40
			 * Return to the previous return path again and continue to return 30;
			 */
		} finally {
			a = 40;
			return a;//If so, the result is 40.
		}
		// return a;
	}
}

Custom exception

package cn.yuan;

/*
 * java It is impossible to consider all situations, so in actual development, we may need to define exceptions ourselves.
 * If we write a class at will, we can't look at it as an Exception class. If you want your class to be an Exception class, you must inherit from Exception or RuntimeException
 * 
 * There are two ways:
 * A:Inherit Exception
 * B:Inherit RuntimeException
 */
public class MyException extends Exception {
	public MyException() {
	}

	public MyException(String message) {
		super(message);
	}
} 
package cn.yuan;

import java.util.Scanner;

/*
 * Custom exception test class
 */
public class StudentDemo {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter student grade:");
		int score = sc.nextInt();

		Teacher t = new Teacher();
		try {
			t.check(score);
		} catch (MyException e) {
			e.printStackTrace();
		}
	}
} 

class Teacher {
	public void check(int score) throws MyException {
		if (score > 100 || score < 0) {
			throw new MyException("Score must be 0-100 between");
		} else {
			System.out.println("There's no problem with the score");
		}
	}

	// Inherited from RuntimeException for MyException
	// public void check(int score) {
	// if (score > 100 || score < 0) {
	// throw new MyException();
	// } else {
	// System.out.println("no problem with score");
	// }
	// }
}

Abnormal precautions

package cn.yuan;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * Abnormal precautions:
 * A:When a subclass overrides a parent method, the subclass's method must throw the same exception or a subclass of the parent exception. (the father is bad, and the son can't be worse than his father)
 * B:If the parent class throws multiple exceptions, when overriding the parent class, the child class can only throw the same exceptions or its subset, and the child class cannot throw exceptions that the parent class does not have
 * C:If the overridden method does not throw an exception, the subclass method must not throw an exception. If an exception occurs in the subclass method, the subclass can only try, not throw
 */
public class ExceptionDemo {

}

class Fu {
	public void show() throws Exception {
	}

	public void method() {
	}
}

class Zi extends Fu {
	@Override
	public void show() throws ArithmeticException {

	}

	@Override
	public void method() {
		// String s = "2021-10-09";
		// SimpleDateFormat sdf = new SimpleDateFormat();
		// Date d = sdf.parse(s);
		// System.out.println(d);
	}
}

Posted by AliasXNeo on Sat, 09 Oct 2021 02:51:24 -0700