Getting started with JavaSE 26: Java Exception Handling analysis (II)

Source: Internet
Author: User

Getting started with JavaSE 26: Java Exception Handling analysis (II)
Seven throws/throw keywords

If a method does not capture a check exception, the method must be declared using the throws keyword. Place the throws keyword in the method Signature

. You can also use the throw keyword to throw an exception, whether it is newly instantiated or captured. Throw the exception

); Throws -- declare the type of exception to be thrown (Declaration ).

The following method declaration throws a RemoteException:

 

import java.io.*;public class ClassName{public void deposit(double amount) throws RemoteException{//Method implementation                throw new RemoteException();        }        //Remainder of class definition}

 

One method can declare that multiple exceptions are thrown, and multiple exceptions are separated by commas.

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}

 

Eight finally keywords

The finally keyword is used to create a code block that is executed after the try code block. No matter whether an exception occurs or not, the code in the finally code block is always executed. In

In the finally code block, you can run statements such as cleanup type and final aftermath. The finally code block appears at the end of the catch code block. The syntax is as follows:

 

Try {// program code} catch (exception type 1 Abnormal variable name 1) {// program code} catch (exception type 2 abnormal variable name 2) {// program code} finally {// program code}

 

Example: Test. java source file code:

 

public class Test{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 example compilation and running results are as follows:

 

The exception is that the array subscript is out of bounds. The statements in the finally block are still executed.

 

Note the following:

1) catch cannot exist independently of try.

2) adding finally blocks after try/catch is not mandatory.

3) After try code, neither catch Block nor finally block can be found.

4) no code can be added between try, catch, and finally blocks.

9. custom exception

You can customize exceptions in Java. Note the following when writing your own exception classes:

1) All exceptions must be subclasses of Throwable.

2) If you want to write a checking Exception class, you must inherit the Exception class.

3) If you want to write a runtime exception class, you must inherit the RuntimeException class.

To use a custom exception, follow these steps:

1. Declare your own Exception class by inheriting the java. lang. Exception class.

2. generate an instance with a custom exception at an appropriate position in the method and throw it with the throw statement.

3. In the declaration part of the method, use the throws statement to declare the exceptions that may be thrown by the method.

You can define your own exception classes as follows:

 

class MyException extends Exception{}

 

Only the Exception class created by the Exception class is the checking Exception class.

The following InsufficientFundsException class is a user-defined Exception class that inherits from Exception. An exception class is the same as any other class,

Contains variables and methods.

Instance:

InsufficientFundsException. java source file code:

 

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 classes,

The following CheckingAccount class contains a withdraw () method that throws an InsufficientFundsException exception.

CheckingAccount. java source file code:

 

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 BankDemo program demonstrates how to call the deposit () and withdraw () Methods of the CheckingAccount class.

BankDemo. java source file code:

 

public class BankDemo{public static void main(String [] args){CheckingAccount c = new CheckingAccount(101);                System.out.println("Depositing $500...");                c.deposit(500.00);                try{              System.out.println("\nWithdrawing $100...");                      c.withdraw(100.00);                      System.out.println("\nWithdrawing $600...");                      c.withdraw(600.00);                }catch(InsufficientFundsException e){                      System.out.println("Sorry, but you are short $" + e.getAmount());                      e.printStackTrace();               }        }}

 

Compile the above three files (in the same package) and run the BankDemo program. The result is as follows:

 

10-way usage exception

 

Two types of exceptions and errors are defined in Java.

JVM (Java Virtual Machine) Exceptions: exceptions or errors thrown by JVM. For example: NullPointerException class,

ArrayIndexOutOfBoundsException class, ClassCastException class.

Program-level exceptions: Exceptions thrown by programs or API programs. For example, the IllegalArgumentException class and the IllegalStateException class.

11 handling exceptions

1. When handling runtime exceptions, the logic is used to reasonably circumvent and assist in try-catch processing.

2. After multiple catch blocks, you can add a catch (Exception) to handle exceptions that may be missed.

3. for uncertain code, you can also add try-catch to handle potential exceptions.

4. Try to handle exceptions. Do not simply call printStackTrace () to print the output.

5. Determine how to handle exceptions based on different business needs and types of exceptions.

6. Try to add finally statement blocks to release the occupied resources.

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.