1, the establishment of exception package, writing Testexception.java program, the main method has the following code, to determine the possible exceptions, for capture processing.
public class Yichang {public
static void Main (string[] args) {for
(int i=0;i<4;i++) {
int k;
switch (i) {case
0:int zero=0;
try{
K=911/zero;
} catch (ArithmeticException e) {
System.out.println ("There is an arithmetic exception!") ");
}
break;
Case 1:
try{
int b[]=null;
k = b[0];
} catch (NullPointerException e) {
System.out.println ("NULL pointer exception occurred!") ");
}
break;
Case 2:
int c[]=new int[2];
try{
k=c[9];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println ("An array ordinal overflow occurred!") ");
}
break;
Case 3:
try{
char ch= "abc". CHARAT ()
catch (Stringindexoutofboundsexception e) {
System.out.println ("Data type conversion exception occurred!") ");
}
Break;}}}
2, set up a exception package, set up a bank class, the class has variable double balance means deposit, Bank class construction method can increase deposit, bank class has the method of withdrawing money withdrawal (double damount), When the amount of withdrawals is greater than the deposit, throw insufficientfundsexception, withdraw the amount of negative, throw nagativefundsexception, such as the new Bank (100), said deposited in the Bank 100 Yuan, Withdrawal (-15) is thrown out of the definition exception when using the method withdrawal.
public class Insufficientfundsexception extends Exception {public
String getMessage () {return
"your balance is insufficient!" ";
}
}
public class Nagativefundsexception extends exception{public
String getMessage () {return
"the withdrawal amount cannot be negative!" ";
}
}
public class Bank {
private static double balance;
Bank () {
};
Bank (double balance) {
this.balance=balance
}
public static void withdrawal (double damount) throws insufficientfundsexception,nagativefundsexception{
if ( damount>balance) {
throw new insufficientfundsexception ();
}
if (damount<0) {
throw new nagativefundsexception ();
}
}
public static void Main (string[] args) {
Bank b=new Bank;
System.out.println ("I have +balance+" Yuan deposit!) ");
try{
withdrawal ();
catch (Insufficientfundsexception | Nagativefundsexception e) {
e.printstacktrace ();
}
try{
withdrawal ( -15);
} catch (Nagativefundsexception | Insufficientfundsexception e) {
e.printstacktrace ();}}}
Together on the topic of Java exception handling to introduce so many people, I hope to help you, if you have any questions welcome to my message, small series will promptly reply to everyone, here also thank you for your support cloud Habitat community site!