Click to enter _ more _java thousand ask
1. How to define your own exceptions
Java supports its own creation of exceptions. See the exceptions here: what is an exception in Java
Here's how:
1. All exceptions must be throwable subclasses.
2. If you want to write a check exception, you need to extend the exception class .
3. If you want to write a run-time exception, you need to extend the RuntimeException class .
4. The exception class, like any other class, can contain fields and methods .
We can define our own exception-handling classes as follows:
Class MyException extends exception{}
Example:
Import java.io.*;p ublic class Insufficientfundsexception extends Exception{private double amount;public Insufficientfundsexception (double amount) {This.amount = amount;} Public double Getamount () {return amount;}}
to prove our use of user-defined exceptions, the following Checkingaccount class contains a withdraw () method that throws a insufficientfundsexception.
Import java.io.*;p ublic 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) throwsinsufficientfundsexception{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 calling the deposit () and withdraw () methods.
public class Bankdemo{public static void Main (String [] args) {Checkingaccount c = new Checkingaccount (101); System.out.println ("depositing ..."); C.deposit (500.00); Try{system.out.println ("Withdrawing $ ..."); C.withdraw (100.00); System.out.println ("Withdrawing ..."); C.withdraw (600.00);} catch (Insufficientfundsexception e) {System.out.println ("Sorry, but is short $" + e.getamount ()); e.printstacktrace ();}}}
compile all of the above three files and run Bankdemo, which will produce the following results:
Depositing ...
Withdrawing ...
Withdrawing ...
Sorry, but is short $200.0
Insufficientfundsexception
At Checkingaccount.withdraw (checkingaccount.java:25)
At Bankdemo.main (bankdemo.java:13)
Java Technology _java thousand questions (0025) _ How to customize exceptions