catalogue
1. There is an exception. There is a difference between adding try catch and not adding try catch
3. How to make finally not output
4. Add return to the statement
1. List at least five common exceptions
2. List five keywords of exceptions
3. Difference between throws and throw
4. What is the difference between final and finally and finalize?
5.finally when not to execute.
6. Difference between exception and error.
I try-catch
1. There is an exception. There is a difference between adding try catch and not adding try catch
1) No try catch
package com.gongsi.cn.oa.work805.test1; import java.util.Scanner; public class BaiDuServer { public static void main(String[] args) { System.out.println("Baidu server has been started"); System.out.println("Baidu server provides services to thousands of people"); Scanner input=new Scanner(System.in); System.out.print("Please enter any character:"); int i=input.nextInt(); System.out.println("The information you entered is:"+i); System.out.println("Baidu server helps you process information"); } }
It will not be executed after an exception occurs
2) Add try catch
package com.gongsi.cn.oa.work805.test1; import java.util.Scanner; public class BaiDuServer { public static void main(String[] args) { System.out.println("Baidu server has been started"); System.out.println("Baidu server provides services to thousands of people"); Scanner input=new Scanner(System.in); System.out.print("Please enter any character:"); try {//try int i=input.nextInt(); System.out.println("The information you entered is:"+i); System.out.println("Baidu server helps you process information"); } catch (Exception e) {//catch System.out.println("Exception handling, treatment!!!"); } System.out.println("Baidu server continues to run and do other things......"); } }
After catching the exception, execute the statements in catch, and then continue to execute in order
2.try-catch-finally
package com.gongsi.cn.oa.work805.test2; import java.util.Scanner; public class TestException { public static void main(String[] args) { try {//Catch exception Scanner scanner=new Scanner(System.in); System.out.println("Turn on the gas...."); System.out.println("Stir fry"); System.out.print("Did I fry it? Enter 0 to focus:"); int b=scanner.nextInt(); int r=8/b; System.out.println("The food is delicious. It's for people to eat!"); //System.exit(0); //return; } catch (Exception e) {//Execute in case of exception e.printStackTrace(); System.out.println("Used to feed pigs"); //return; //System.exit(0); }finally {//Will be implemented System.out.println("Turn off the gas!");//finally, when is system. Not executed exit(0); } //System. out. Println ("the statement after the return end method cannot be executed here"); } }
In case of abnormality:
When there are no exceptions:
It can be seen that the statements in finally will be executed whether there are exceptions or not. (when will it not be implemented? It will be discussed below)
2.try-catch-catch-finally
package com.gongsi.cn.oa.work805.test2; import java.util.InputMismatchException; import java.util.Scanner; public class TestException2 { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); try { System.out.println("Go to hospital "); System.out.println("Doctor: what's wrong with you?"); System.out.print("patient:"); // String s="null"; // System.out.println(s.length()); int b=scanner.nextInt(); int r=8/b; System.out.println("Not sick"); }catch (ArithmeticException ae) { ae.printStackTrace(); System.out.println("Doctor treatment ArithmeticException Types of diseases"); }catch (InputMismatchException ime) { ime.printStackTrace(); System.out.println("Doctor treatment InputMismatchException Types of diseases"); }catch (Exception e) { System.out.println("I'm sick....."); System.out.println("Catch a disease whose name is unknown, and the doctor doesn't know how to deal with it...."); }finally { System.out.println("Get out of the hospital..."); } } }
try , catch , finally , equivalent to polymorphism
3. How to make finally not output
Finally, whether an exception occurs or not, it will be executed. Function: used to close resources: close database connection and file input / output stream. Finally, the only one that is not executed: exit(0);exit(1); When a return statement is encountered, finally is also executed.
package com.gongsi.cn.oa.work805.test2; import java.util.Scanner; public class TestException { public static void main(String[] args) { try {//Catch exception Scanner scanner=new Scanner(System.in); System.out.println("Turn on the gas...."); System.out.println("Stir fry"); System.out.print("Did I fry it? Enter 0 to focus:"); int b=scanner.nextInt(); int r=8/b; System.out.println("The food is delicious. It's for people to eat!"); System.exit(0); //return; } catch (Exception e) {//Execute in case of exception e.printStackTrace(); System.out.println("Used to feed pigs"); //return; System.exit(0); }finally {//Will be implemented System.out.println("Turn off the gas!");//finally, when is system. Not executed exit(0); } //System. out. Println ("the statement after the return end method cannot be executed here"); } }
finally, I found that the sentence "turn off the gas" would not be executed
4. Add return to the statement
return: the next statement will not be executed
package com.gongsi.cn.oa.work805.test2; import java.util.Scanner; public class TestException { public static void main(String[] args) { try {//Catch exception Scanner scanner=new Scanner(System.in); System.out.println("Turn on the gas...."); System.out.println("Stir fry"); System.out.print("Did I fry it? Enter 0 to focus:"); int b=scanner.nextInt(); int r=8/b; System.out.println("The food is delicious. It's for people to eat!"); //System.exit(0); return; } catch (Exception e) {//Execute in case of exception e.printStackTrace(); System.out.println("Used to feed pigs"); //return; //System.exit(0); }finally {//Will be implemented System.out.println("Turn off the gas!");//finally, when is system. Not executed exit(0); } System.out.println("return The statement after the end method cannot be executed here"); } }
II Throws and Throw
1. Differences
1) Location
* throws appears after the method
* throw appears in the method
2) Number of exceptions thrown
* throws can throw multiple exception types
* throw can only throw one exception object
3) Function
* throws declares that exceptions may occur in this method, telling programmers to be careful and handle them when calling.
* throw directly throws an explicit exception object.
4) Throw exception type
* throws throw type
* throw object
2. Examples
Check time exception (run time exception is described below)
When checking for exceptions, be sure to add try catch
package com.gongsi.cn.oa.work805.test2; import javax.swing.JOptionPane; //When checking for exceptions, be sure to add try catch public class TestThrow { public static void main(String[] args) { int a=8; int b=0; int r=0; try { r=div(a, b); System.out.println(r); } catch (Exception e) { e.printStackTrace();//For programmers to see, programmers understand String msg=e.getMessage();//Show it to the customer System.out.println(msg); JOptionPane.showConfirmDialog(null, msg); } } //throws declares that exceptions may occur in this method. It tells programmers to be careful and handle them when calling public static int div(int a,int b) throws DivNotZeroException{ if (b==0) { throw new DivNotZeroException("Divisor cannot be 0"); } int result=a/b; return result; } }
III Custom exception
1. Steps
1) Customize an Exception class to inherit Exception (check Exception) or RunTimeException (runtime Exception)
2) Write an exception constructor and inherit the constructor of the parent class
3) Add the throws exception class after the method
4) Create an exception class object inside the method and Throw it
2. Example 1
Runtime exception} inherits the parent RuntimeException
1) Customize an exception class
package com.gongsi.cn.oa.work805.test3; //Runtime exception inherits the parent RuntimeException public class DivNotZeroException extends RuntimeException { public DivNotZeroException() { super(); // TODO Auto-generated constructor stub } public DivNotZeroException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public DivNotZeroException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public DivNotZeroException(String message) { super(message); // TODO Auto-generated constructor stub } public DivNotZeroException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }
2) Construction method generation:
3) Add the Throw exception class after the method, create an exception class object inside the method and Throw it
package com.gongsi.cn.oa.work805.test3; //For runtime exceptions, try catch may not be added import javax.swing.JOptionPane; public class TestThrow { public static void main(String[] args) { int a=8; int b=0; int r=0; r=div(a, b); System.out.println(r); } //throws declares that exceptions may occur in this method. It tells programmers to be careful and handle them when calling public static int div(int a,int b) throws DivNotZeroException{ if (b==0) { throw new DivNotZeroException("Divisor cannot be 0"); } int result=a/b; return result; } }
You can not add try catch to report an error after running
3. Example 2
The custom abnormal gender can only be male or female, and the age is between 1 and 150
package com.gongsi.cn.oa.work805.test4; //The custom abnormal gender can only be male or female, and the age is between 1 and 150 public class Student { private String name; private String sex; private String address; private int age; public Student(String name, String sex, String address, int age) { super(); this.name = name; this.sex = sex; this.address = address; this.age = age; } public int getAge() { return age; } public void setAge(int age) throws AgeException{ if (age<1||age>150) { throw new AgeException("Age can only be 1~150 between"); } this.age = age; } public Student() { super(); } public Student(String name, String sex, String address) { super(); this.name = name; this.sex = sex; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } //There may be an exception in declaring this method. The caller should handle it carefully public void setSex(String sex) throws SexException{ if (!(sex.equals("male")||sex.equals("female"))) { throw new SexException("Gender can only be male or female");//An exception object is actually thrown } this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
package com.gongsi.cn.oa.work805.test4; //Custom gender exception public class SexException extends Exception { public SexException() { super(); // TODO Auto-generated constructor stub } public SexException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public SexException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public SexException(String message) { super(message); // TODO Auto-generated constructor stub } public SexException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }
package com.gongsi.cn.oa.work805.test4; //Custom age exception public class AgeException extends Exception { public AgeException() { super(); // TODO Auto-generated constructor stub } public AgeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public AgeException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public AgeException(String message) { super(message); // TODO Auto-generated constructor stub } public AgeException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }
package com.gongsi.cn.oa.work805.test4; import javax.swing.JOptionPane; //The custom abnormal gender can only be male or female, and the age is between 1 and 150 public class TestStudent { public static void main(String[] args) { Student student=new Student(); try { student.setSex("male");//When the age is abnormal, the next statement will not be executed, that is, setAge will not be executed student.setAge(155); System.out.println(student.getSex()); } catch (SexException se) { se.printStackTrace(); JOptionPane.showConfirmDialog(null, se.getMessage()); } catch (AgeException ae) { ae.printStackTrace(); JOptionPane.showConfirmDialog(null, ae.getMessage()); }catch (Exception e) { JOptionPane.showConfirmDialog(null, "An unknown exception occurred"); }finally { System.out.println("Close resource!"); } } }
IV Some interview questions
1. List at least five common exceptions
1) Null pointerexception null pointer exception
2)ClassNotFoundException "class found no exception"
One of the most difficult exceptions to find. That is, under the bin directory The class file is gone. The solution is to recompile it.
3)ArrayIndexOutOfBoundsException array index out of bounds exception
4)ClassCastException class conversion exception
5)ArithmeticException math exception
6) Inputmismatch exception input mismatch exception
2. List five keywords of exceptions
try catch finally throw throws
3. Difference between throws and throw
As mentioned above
4. What is the difference between final and finally and finalize?
1) final: final, final version, used to modify variables and become constants
The modified class is the final version of the class and does not inherit from other classes.
Modification repetition is the final version of the method, which is not overridden by subclasses
2) finally is the keyword in exception handling, which indicates the statement block to be executed regardless of whether an exception occurs. The only case not to be executed is exit (0) and exit (1)
3)finalize; Is a method in Object, which is used to release resources before recycling to the garbage collector.
5.finally when not to execute.
exit(0),exit(1)
6. Difference between exception and error.
1) Error: error is a very serious problem that cannot be solved. Do not try to solve these problems, such as memory overflow
2) Exception: exceptions have been checked. The program has been checked, but there are still inevitable problems due to external factors. Developers are required to deal with these exceptions in advance
3) RuntimeException: unchecked exception is an exception caused by the programmer's failure to carefully check the program. The compiler puts all the responsibility on the programmer, that is, the compiler will not check for you and does not require you to deal with it