前言
java异常类的实现
以下是本篇文章正文内容,下面案例可供参考
一、NumberFormatException 实现
package example;
import java.util.Scanner;
public class example13 {
public static void main(String[] args) {
String s="JAVA";
Scanner reader=new Scanner(System.in);
try {
int i=Integer.parseInt(s);
System.out.println(s);
}catch (NumberFormatException e) {
// TODO: handle exception
System.out.println(e);
}
finally {
}
}
}
二、ArrayIndexOutOfBoundsException实现
package example;
import java.util.Scanner;
public class example12 {
public static void main(String[] args) {
Scanner reader =new Scanner(System.in);
int []a=new int [5];
try {
System.out.println("11111111111");
for(int i=0;reader.hasNextInt();i++) {
a[i]=reader.nextInt();
}
System.out.println("222222222222");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界");
System.out.println(e.getMessage());
System.out.println(e);
}
}
}
三、自定义异常类实现
package example;
public class example14 {
public static void main(String[] args) {
student s=new student();
try {
s.setname("afafa");
s.setaddress("sssss");
}catch(IllegaNameException e) {
System.out.println(e);
}catch(IllegalAddressException e){
System.out.println(e);
}finally {
}
}
}
class IllegaNameException extends Exception{
int message;
public IllegaNameException(String s) {
}
}
class IllegalAddressException extends Exception{
public IllegalAddressException(String s) {
}
}
class student{
String name;
String address;
public void setname(String s) throws IllegaNameException {
if(s.length()<1||s.length()>5)
throw new IllegaNameException(s);
}
public void setaddress(String s) throws IllegalAddressException{
int flag=0;
for(int i=0;i<s.length();i++) {
if(s.indexOf("省")!=0||s.indexOf("市")!=0) {
flag++;
}
}
if(flag!=2)
throw new IllegalAddressException(s);
}
}