The best Java exception handling Tutorial In 2024, In this tutorial you can learn Exception class hierarchy,Built-in Java exception class,Anomaly,Catch the exception,Multiple catch blocks,throws / throw Keywords:,finally keyword,Statement custom exception,General exception,
Exceptions are some errors in the program, but not all errors are exceptions, and sometimes mistakes can be avoided.
For example, your code less a semicolon, then run out of the results is to prompt wrong java.lang.Error; if you use System.out.println (11/0), then you are doing because you use a divisor 0 It will be thrown java.lang.ArithmeticException exception.
There are many reasons for an exception occurs, usually contains the following categories:
These exceptions either because of user error caused some procedural errors caused because there are other physical errors. -
To understand Java exception handling is how it works, you need to have the following three types of exceptions:
All exception classes inherit from java.lang.Exception subclass.
Exception class is a subclass of Throwable class. In addition to the Exception class, Throwable there is a subclass of Error.
Java programs usually do not catch the error. Error generally occurs when a serious fault, they are visible outside Java program processing.
Error runtime environment used to indicate an error occurs.
For example, JVM memory overflow. In general, the program does not recover from the error.
Exception class has two main sub-categories: IOException class and RuntimeException class.
Built-in Java class (the next will be explained), it has most of the usual checks and unchecked exception.
Java language defines several exception classes in the standard java.lang package.
Standard runtime exception classes are subclasses of the most common exception classes. Since java.lang package is loaded by default to all Java programs, so most from the runtime exception classes inherited abnormalities can be used directly.
According to various Java class library also defines a number of other exceptions, the following table lists the Java unchecked exception.
abnormal | description |
---|---|
ArithmeticException | When the abnormal operation conditions, this exception is thrown. For example, an integer "divide by zero" thrown an instance of this class. |
ArrayIndexOutOfBoundsException | With an illegal index to access an array thrown. If the index is negative or greater than or equal size of the array, the index is illegal index. |
ArrayStoreException | Trying to store the wrong type of object into an array of exceptions thrown. |
ClassCastException | When you try to cast an object is not an instance of a subclass Thrown. |
IllegalArgumentException | Thrown to indicate that the method has been passed an illegal or inappropriate argument. |
IllegalMonitorStateException | Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other objects are waiting thread monitor without the monitor specified. |
IllegalStateException | In the case of an illegal or inappropriate time to call a method to generate a signal. In other words, the Java environment or Java application is not in an appropriate state for the requested operation. |
IllegalThreadStateException | Thread is not in an appropriate state when requested operation required thrown. |
IndexOutOfBoundsException | It indicates a sort index (such as sorting an array, a string or vector) thrown out of range. |
NegativeArraySizeException | If an application tries to create an array with negative size, Thrown. |
NullPointerException | When an application attempts to use an object in need of local null when Thrown |
NumberFormatException | When an application tries to convert a string into a numeric type, but that the string can not be converted to the appropriate format, dished out the anomaly. |
SecurityException | By the security manager throws an exception, it indicates a security violation. |
StringIndexOutOfBoundsException | This exception from the String throws methods to indicate that an index is either negative or greater than the size of the string. |
UnsupportedOperationException | When the requested operation is not supported Thrown. |
The following table lists the Java defined in the java.lang package checked exception classes.
abnormal | description |
---|---|
ClassNotFoundException | Application tries to load the class, you can not find the corresponding class Thrown. |
CloneNotSupportedException | When you call the Object class clone method to clone an object, but the object's class can not implement Cloneable an interface Thrown. |
IllegalAccessException | When denied access to a class Thrown. |
InstantiationException | When you try to use the Class class newInstance create an instance of a class method, designated class object because it is an interface or an abstract class can not be instantiated, dished out the anomaly. |
InterruptedException | A thread is interrupted by another thread, this exception is thrown. |
NoSuchFieldException | Variable requested does not exist |
NoSuchMethodException | Method requested does not exist |
The following list is the main method Throwable class:
No. | Method and Description |
---|---|
1 | public String getMessage () Returns detailed information about the exception occurred. The news initialized in the constructor of Throwable class. |
2 | public Throwable getCause () Returns a Throwable object that represents the reason for the exception. |
3 | public String toString () Results using the getMessage () returns the name of the class of Cascade. |
4 | public void printStackTrace () Print toString () result and stack level to System.err, namely the error output stream. |
5 | public StackTraceElement [] getStackTrace () It returns an array containing a stack level. 0 subscript element represents the top of the stack, the last element represents a method call stack bottom of the stack. |
6 | public Throwable fillInStackTrace () Throwable object stack is filled with the current level of the call stack level, added to the stack level of any previous information. |
Use try and catch keywords can catch the exception. try / catch block in place exceptions that might occur.
Syntax try / catch block code is called a protection code using try / catch is as follows:
try { // 程序代码 }catch(ExceptionName e1) { //Catch 块 }
Catch statement contains an exception to capture the type of statement. When the protection code block when an exception occurs, try the back of the catch block will be checked.
If the exception contained in the catch block, the exception will be passed to the catch block, and pass a parameter to this method is the same.
The following example has declared a two-element array, when the code tries to access the third element of the array when it will throw an exception.
// 文件名 : ExcepTest.java import java.io.*; public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } }
The above code compile and run the following output:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block
A plurality of catch code blocks after the code block is called a try to follow multiple capture.
Multiple catch block syntax is as follows:
try{ // 程序代码 }catch(异常类型1 异常的变量名1){ // 程序代码 }catch(异常类型2 异常的变量名2){ // 程序代码 }catch(异常类型2 异常的变量名2){ // 程序代码 }
The above code snippet contains three catch blocks.
You can add any number of catch blocks behind the try statement.
If an exception occurs in the protection code, an exception is thrown to the first catch block.
If you throw the data type mismatch exception of ExceptionType1, where it will be captured.
If not, it will be transferred to the second catch block.
So, until the exception is caught by any catch or block.
This example shows how using multiple try / catch.
try { file = new FileInputStream(fileName); x = (byte) file.read(); }catch(IOException i) { i.printStackTrace(); return -1; }catch(FileNotFoundException f) //Not valid! { f.printStackTrace(); return -1; }
If a method does not capture a checked exception, then the method must use the throws keyword to declare. throws keyword placed at the end of the method signature.
You can also use the keyword throw throw an exception, whether it is new or newly instantiated captured.
The following method declaration throws a RemoteException exception:
import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition }
A method can be declared to throw multiple exceptions, separated by a comma between multiple exceptions.
For example, the following method declaration throws RemoteException and InsufficientFundsException:
import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } //Remainder of class definition }
finally keyword is used to create the code blocks after the code block try to perform.
Whether or not an exception occurs, finally code block code will always be executed.
In the finally block, you can run clean up the aftermath of the nature of the type of ending statement.
finally block appears in the catch block Finally, the syntax is as follows:
try{ // 程序代码 }catch(异常类型1 异常的变量名1){ // 程序代码 }catch(异常类型2 异常的变量名2){ // 程序代码 }finally{ // 程序代码 }
public class ExcepTest{ public static void main(String args[]){ int a[] = new int[2]; try{ System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } finally{ a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); } } }
The above examples compiled results are as follows:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
Note that the following matters:
In Java, you can customize exception. The following points need to remember to write your own exception classes.
You can define your own exception class like this:
class MyException extends Exception{ }
Only inherit Exception class to create exception classes are checked exception classes.
The following InsufficientFundsException class is a user-defined exception class that inherits from Exception.
An exception class and any other classes, contains variables and methods.
// 文件名InsufficientFundsException.java import java.io.*; public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } }
To demonstrate how to use our custom exception class,
In the following CheckingAccount class contains a withdraw () method throws an exception InsufficientFundsException.
// 文件名称 CheckingAccount.java import java.io.*; public class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } public double getBalance() { return balance; } public int getNumber() { return number; } }
The following program demonstrates how to call BankDemo CheckingAccount class deposit () and withdraw () method.
//文件名称 BankDemo.java public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500/en."); c.deposit(500.00); try { System.out.println("\nWithdrawing $100/en."); c.withdraw(100.00); System.out.println("\nWithdrawing $600/en."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $" + e.getAmount()); e.printStackTrace(); } } }
Compile the above three files, and run the program BankDemo, get the results as follows:
Depositing $500/en. Withdrawing $100/en. Withdrawing $600/en. Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13)
It defines two types of exceptions and errors in Java.