abnormal
Exceptions are errors in the program. But not all errors are exceptions, and errors can sometimes be avoided.
Classification of exceptions:
- **Checking exceptions: * * the most representative checking exceptions are those caused by user errors or problems, which cannot be foreseen by programmers. For example, when you want to open a nonexistent file, an exception occurs. These exceptions cannot be simply ignored at compile time.
- Runtime exceptions: runtime exceptions are exceptions that may be avoided by programmers. In contrast to checking exceptions, runtime exceptions can be ignored at compile time.
- Error: an error is not an exception, but a problem out of the programmer's control. Errors are usually ignored in code. For example, when the stack overflows, an error occurs and cannot be checked at compile time.
Example:
package com.wmwx.exception; public class Demo01 { public static void main(String[] args) { new Demo01().a(); //Exception thrown: StackOverflowError System.out.println(11/0); //Exception thrown: ArithmeticException System.out.println() //Throw exception: Error } public void a(){ b(); } public void b(){ a(); } }
Exception architecture
Java treats exceptions as objects and defines a base class java Lang. throwable is the superclass of all exceptions. These exceptions are divided into two categories: Exception and Error. The Exception class has two main subclasses, namely IOException and RuntimeException.
Error
The Error class object is generated and thrown by the virtual machine. Most errors have nothing to do with the operation performed by the coder.
Common errors, such as the Java virtual machine running error, will occur when the JVM no longer has the memory resources required to continue the operation. When these exceptions occur, the Java virtual machine will generally choose to abort the thread.
There are also errors that occur when the virtual machine attempts to execute an application, such as NoClassDefFoundError, LinkageError, etc. these errors are not traceable because they are outside the control and processing capabilities of the application, and most of them are not allowed when the program is running.
Exception
In the branch of Exception class, there is an important subclass RuntimeException (runtime Exception), which contains the following exceptions:
- ArrayIndexOutOfBoundsException (array subscript out of bounds)
- NullPointerException (null pointer exception)
- ArithmeticException (arithmetic exception)
- MissingResourceException (missing resource)
- ClassNotFoundException (class not found)
These exceptions are not checked. The program can choose to capture and handle them or not. These exceptions are generally caused by program logic errors. The program should avoid such exceptions as much as possible from a logical point of view.
Difference between Error and Exception:
- Error is usually a catastrophic and fatal error that cannot be controlled and handled by the program. When these exceptions occur, the Java virtual machine (JVM) will generally choose to terminate the thread
- Exception s can usually be handled by the program, and these exceptions should be handled as much as possible in the program.
Catch exception
Use the try and catch keywords to catch exceptions. try/catch code blocks are placed where exceptions can occur.
The code in the try/catch code block is called protection code, and its basic syntax is as follows:
try { // Program code }catch(ExceptionName e1) { // Catch block }catch(ExceptionName e2) //e2 needs to be larger than e1 { // Catch block }finally { // It will be implemented eventually }
Example:
package com.wmwx.exception; public class Demo02 { public static void main(String[] args) { int a = 11; int b = 0; //Shortcut key ctrl+alt+T try{ //try monitoring area System.out.println(a/b); }catch (ArithmeticException e){ //Catch catch exception (parameter is exception type) System.out.println("Program exception, variable b Cannot be 0!"); }finally { //finally, rehabilitation work System.out.println("finally Will eventually be implemented."); } try{ //Monitoring area new Demo02().a(); }catch (StackOverflowError e){ //Catch exceptions. Multiple categories need to be from small to large System.out.println("StackOverflowError"); //Will output }catch (Exception e){ System.out.println("Exception"); //No output }catch (Throwable t){ System.out.println("Throwable"); //No output }finally { //dealing with the aftermath System.out.println("finally Will eventually be implemented."); } } public void a(){ b(); } public void b(){ a(); } }
Throw exception
If a method does not catch a checking exception, the method must be declared using the throws keyword. The throws keyword is placed at the end of the method signature.
You can also throw an exception using the throw keyword, whether it is newly instantiated or just caught.
Note: the spelling of the two methods is different. The first has an s at the end and the second does not.
Example:
package com.wmwx.exception; public class Demo03 { public static void main(String[] args) { int a = 11; int b = 0; try { new Demo03().devide(a, b); } catch (ArithmeticException e) { e.printStackTrace(); } finally { } } //Assuming that exceptions cannot be handled in the method, you can actively throw exceptions with throws public void devide(int a, int b) throws ArithmeticException{ if (b==0){ throw new ArithmeticException(); //Throw is used to actively throw exceptions, which is generally used in methods } System.out.println(a / b); } }
Custom exception
Using Java's built-in Exception class can describe most of the exceptions that occur during programming. In addition, users can customize exceptions by inheriting the Exception class.
Example:
MyException class (custom exception class):
package com.wmwx.exception; //Custom exception class public class MyException extends Exception{ //Suppose: an exception is thrown when the number passed is greater than 10 private int detail; //Construction method public MyException(int a) { this.detail = a; } //toString print exception information @Override public String toString() { return "MyException{detail=" + detail + "}"; } }
Demo04 class (test class):
package com.wmwx.exception; //Custom exception test class public class Demo04 { //There may be abnormal methods public void test(int a) throws MyException { System.out.println("The parameters passed are:"+a); if (a>10){ throw new MyException(a); //Throw exception } System.out.println("No exceptions!"); } public static void main(String[] args) { try { new Demo04().test(5); //No exceptions new Demo04().test(15); //Abnormal } catch (MyException e) { System.out.println("MyException => " + e); } } }
summarize experience
- When dealing with run-time exceptions, logic is used to avoid them reasonably, and try catch processing is assisted at the same time.
- After multiple catch blocks, you can add a catch (Exception) to handle exceptions that may be missed. For uncertain code, you can also add try catch to handle potential exceptions.
- Try to handle exceptions, and never simply call printStackTrace() to print out. How to handle exceptions should be determined according to different business requirements and exception types.
- Try to add finally statement blocks to release the occupied resources.