1. What is an exception?
First, let's take a look at the example in the figure below:
In this example, the error code exists by dividing by 0. Exception due to dividing by 0: ArithmeticException
HelloException.java
package com.yiibai.tutorial.exception;public class HelloException { public static void main(String[] args) { System.out.println("Three"); // This division no problem. int value = 10 / 2; System.out.println("Two"); // This division no problem. value = 10 / 1; System.out.println("One"); // This division has problem, divided by 0. // An error has occurred here. value = 10 / 0; // And the following code will not be executed. System.out.println("Let's go!"); }}Running this example will result:
You can see notifications on the console screen. Error notifications are very clear, including information on lines of code.
Let's take a look at the following program through the process in the figure below:
We will modify the code of the above-mentioned embodiment.
HelloCatchException.java
package com.yiibai.tutorial.exception;public class HelloCatchException { public static void main(String[] args) { System.out.println("Three"); // This division no problem. int value = 10 / 2; System.out.println("Two"); // This division no problem. value = 10 / 1; System.out.println("One"); try { // This division has problem, divided by 0. // An error has occurred here. value = 10 / 0; // And the following code will not be executed. System.out.println("Value =" + value); } catch (ArithmeticException e) { // The code in the catch block will be executed System.out.println("Error: " + e.getMessage()); // The code in the catch block will be executed System.out.println("Ignore..."); } // This code is executed System.out.println("Let's go!"); }}Running the sample results:
Three
Two
One
Error: / by zero
Ignore...
Let's go!
We will explain the following procedure as follows the flow of the example image.
2. Exception hierarchy <br />This is a model of the hierarchical graph of Java exceptions.
The highest class is: Throwable
The two direct subclasses are Error and Exception.
There is a RuntimeException subclass in exception transfer, including compile-time exceptions not checked for in Java. Check and cancel the check at compile time, as described in the next section of the implementation example.
Note: Your class should inherit from two branches: Error or Exception, not directly from Throwable.
The virtual machine raises this error when a dynamic link fails, or when some other "hard" failure of the virtual machine occurs. Typical Java programs do not catch errors, so Java programs do not throw any errors. Most programs throw and capture objects derived from the Exception class. An exception indicates a problem, but these problems are not serious systemic problems. Most programs you write will throw and catch exceptions.
The Exception class defines many subclasses in the Java package. These subclasses indicate that different types of exceptions may occur. For example, NegativeArraySizeException indicates that the program is trying to create an array of negative size.
A special meaning of a director's subclass in the Java language: The RuntimeException class represents an exception that occurs (during runtime) in a Java virtual machine. An example of a runtime exception is the NullYiibaierException exception, which is raised when a method tries to access a member of an object through a null reference. NullYiibaierException can appear anywhere a program attempts to dereference an object. The benefits of checking for exception catches frequently far outweigh its costs.
Since runtime exceptions are omnipresent, it is futile to try to catch or specify all the time (unreadable and unmaintainable code), the compiler allows runtime exceptions to go uncaught and specify.
The Java package defines several RuntimeException classes. You can catch these exceptions, just like others. But there is no need for a way to specify that it throws a runtime exception. In addition, you can create your own RuntimeException subclass. Runtime Exceptions - The discussion below contains in-depth discussion of when and how to use runtime exceptions. 3. Use try-catch to handle exceptions
Write classes inherited from Exception.
AgeException.java
package com.yiibai.tutorial.exception.basic;public class AgeException extends Exception { public AgeException(String message) { super(message); }}TooYoungException.javapackage com.yiibai.tutorial.exception.basic;public class TooYoungException extends AgeException { public TooYoungException(String message) { super(message); }} TooOldException.java
package com.yiibai.tutorial.exception.basic;public class TooOldException extends AgeException { public TooOldException(String message) { super(message); }} And the static method of checking age for AgeUtils class.
AgeUtils.java
package com.yiibai.tutorial.exception.basic;public class AgeUtils { // This method checks the age. // If age is less than 18, the method will throw an exception TooYoungException // If age greater than 40, the method will throw an exception TooOldException public static void checkAge(int age) throws TooYoungException, TooOldException { if (age < 18) { // If age is less than 18, an exception will be thrown // This method ends here. throw new TooYoungException("Age " + age + " too young"); } else if (age > 40) { // If age greater than 40, an exception will be thrown. // This method ends here. throw new TooOldException("Age " + age + " too old"); } // If age is between 18-40. // This code will be executed. System.out.println("Age " + age + " OK!"); }} Check for exceptions and unchecked exceptions:
AgeException is Exception, subclass of TooOldException and TooYoungException2 are direct subclasses of AgeException, so they are "Checked Exception"
The AgeUtils.checkAge(int) method has thrown an exception and needs to list their method declarations through the keyword "throws". Or you can declare throwing more levels.
The AgeUtils.checkAge(int) location must also be processed to catch the exception or continue to throw it.
"Checked exception" is checked by "Java Compiler".
There are two options:
TryCatchDemo1.java
package com.yiibai.tutorial.exception.basic;public class TryCatchDemo1 { public static void main(String[] args) { System.out.println("Start Recruiting ..."); // Check age System.out.println("Check your Age"); int age = 50; try { AgeUtils.checkAge(age); System.out.println("You pass!"); } catch (TooYoungException e) { // Do something here .. System.out.println("You are too young, not pass!"); System.out.println(e.getMessage()); } catch (TooOldException e) { // Do something here .. System.out.println("You are too old, not pass!"); System.out.println(e.getMessage()); } }} In the following example, we will catch the exception (hyperException class) through the parent class.
TryCatchDemo2.java
package com.yiibai.tutorial.exception.basic;public class TryCatchDemo2 { public static void main(String[] args) { System.out.println("Start Recruiting ..."); // Check age System.out.println("Check your Age"); int age = 15; try { // Here can throw TooOldException or TooYoungException AgeUtils.checkAge(age); System.out.println("You pass!"); } catch (AgeException e) { // If an exception occurs, type of AgeException // This catch block will be executed System.out.println("Your age invalid, you not pass"); System.out.println(e.getMessage()); } }} Different exceptions can also be grouped in blocks to handle if they are handled in the same way to the logical program.
TryCatchDemo3.java
package com.yiibai.tutorial.exception.basic;public class TryCatchDemo3 { public static void main(String[] args) { System.out.println("Start Recruiting ..."); // Check age System.out.println("Check your Age"); int age = 15; try { // Here can throw TooOldException or TooYoungException AgeUtils.checkAge(age); System.out.println("You pass!"); } catch (TooYoungException | TooOldException e) { // Catch multi exceptions in one block. System.out.println("Your age invalid, you not pass"); System.out.println(e.getMessage()); } }} 4. try-catch-finally
We are used to catching errors through try-catch blocks. Try-catch-finally to handle exceptions completely.
try { // Do something here} catch (Exception1 e) { // Do something here} catch (Exception2 e) { // Do something here} finally { // Finally block is always executed // Do something here} TryCatchFinallyDemo.java
package com.yiibai.tutorial.exception.basic;public class TryCatchFinallyDemo { public static void main(String[] args) { String text = "001234A2"; int value = toInteger(text); System.out.println("Value= " + value); } public static int toInteger(String text) { try { System.out.println("Begin parse text: " + text); // An Exception can throw here (NumberFormatException). int value = Integer.parseInt(text); return value; } catch (NumberFormatException e) { // In the case of 'text' is not a number. // This catch block will be executed. System.out.println("Number format exception " + e.getMessage()); // Returns 0 if NumberFormatException occurs return 0; } finally { System.out.println("End parse text: " + text); } }}This is the process of the program. The finally block will always be executed under any circumstances.
5. Surrounding exception
Person.java
package com.yiibai.tutorial.exception.wrap;public class Person { public static final String MALE = "male"; public static final String FEMALE = "female"; private String name; private String gender; private int age; public Person(String name, String gender, int age) { this.name = name; this.gender = gender; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }} GenderException.java
package com.yiibai.tutorial.exception.wrap;// Gender Exception.public class GenderException extends Exception { public GenderException(String message) { super(message); }} ValidateException class package has other exceptions.
ValidateException.java
package com.yiibai.tutorial.exception.wrap;public class ValidateException extends Exception { // Wrap an Exception public ValidateException(Exception e) { super(e); }} ValidateUtils.java
package com.yiibai.tutorial.exception.wrap;import com.yiibai.tutorial.exception.basic.AgeUtils;public class ValidateUtils { public static void checkPerson(Person person) throws ValidateException { try { // Check age. // Valid if between 18-40 // This method can throw TooOldException, TooYoungException. AgeUtils.checkAge(person.getAge()); } catch (Exception e) { // If not valid // Wrap this exception by ValidateException, and throw throw new ValidateException(e); } // If that person is Female, ie invalid. if (person.getGender().equals(Person.FEMALE)) { GenderException e = new GenderException("Do not accept women"); throw new ValidateException(e); } }} WrapperExceptionDemo.java
package com.yiibai.tutorial.exception.wrap;public class WrapperExceptionDemo { public static void main(String[] args) { // One participant recruitment. Person person = new Person("Marry", Person.FEMALE, 20); try { // Exceptions may occur here. ValidateUtils.checkPerson(person); } catch (ValidateException wrap) { // Get the real cause. // May be TooYoungException, TooOldException, GenderException Exception cause = (Exception) wrap.getCause(); if (cause != null) { System.out.println("Not pass, cause: " + cause.getMessage()); } else { System.out.println(wrap.getMessage()); } } }}6. RuntimeException and subclasses The RuntimeException class and its subclasses are both "unchecked exceptions". It is not checked at compile time by the Java compiler. In some cases, you can inherit from this branch to write your own exceptions.
Below are some classes belonging to the RuntimeException branch (of course, this is not all).
Some examples of handling exceptions of this type:
6.1- NullYibaierException
This is the most common exception and usually causes errors in the program. The exception is thrown when you call a method or access an empty object's field.
NullYiibaierExceptionDemo.java
package com.yiibai.tutorial.exception.runtime;public class NullYibaierExceptionDemo { // For example, here is a method that can return null string. public static String getString() { if (1 == 2) { return "1==2 !!"; } return null; } public static void main(String[] args) { // This is an object that references not null. String text1 = "Hello exception"; // Call the method retrieves the string length. int length = text1.length(); System.out.println("Length text1 = " + length); // This is an object that references null. String text2 = getString(); // Call the method retrieves the string length. // NullYiibaierException will occur here. // It is an exception occurs at runtime (type of RuntimeException) // Javac compiler does not force you to use a try-catch block to handle it length = text2.length(); System.out.println("Finish!"); }}Results of running the example:
In reality, try-catch can be used to catch and handle this exception like when handling other exceptions. However, this is mechanical and usually we should check to make sure that the object is not null before using it.
You can correct the above code to make it similar to the following to avoid null pointer exceptions:
// This is a null object.String text2 = getString();// Check to make sure 'Text2' are not null.// instead of using try-catch.if (text2 != null) { length = text2.length();} 6.2- ArrayIndexOfBoundException
This exception occurs when you try to access an array element with an invalid index. For example, an array has 10 elements to access, but you are accessing elements with index 20.
ArrayIndexOfBoundsExceptionDemo.java
package com.yiibai.tutorial.exception.runtime;public class ArrayIndexOfBoundsExceptionDemo { public static void main(String[] args) { String[] strs = new String[] { "One", "Two", "Three" }; // Access to the element has index 0. String str1 = strs[0]; System.out.println("String at 0 = " + str1); // Access to the element has index 5. // ArrayIndexOfBoundsException occur here. String str2 = strs[5]; System.out.println("String at 5 = " + str2); }} To avoid ArrayIndexOfBoundsException, we should check the array more than try-catch.
if (strs.length > 5) { String str2 = strs[5]; System.out.println("String at 5 = " + str2);} else { System.out.println("No elements with index 5");}The above is all about this article, I hope it will be helpful to everyone's learning.