package c;
//方法调用时的异常处理
/*public class Exceptions2 {
public static void main(String args[]){
int x[]={2,5,9};
try{
div d=new div();
d.meth();
x[3]=100;
}catch(ArithmeticException e){
System.out.println("1");
}catch(RuntimeException e){
System.out.println("2");
}catch(Exception e)
{
System.out.println("3");
}
}
}
class div{
void d(int a,int b){
int s=0;
s=a/b;
System.out.println("商:"+s);
}
void meth()
{
d(18,2);
d(3,0);
}
}
//
/*
商:9
1
在方法d()中并没有捕获和处理异常,因此该异常向他的调用者方法meth()抛出,在main中Udine异常进行捕获
*/
class stt{
private String studentNo,name;
void setStudent(String stno,String nm) throws numException{
if(stno.length()!=9)
throw new numException("学号位数不对,应该是9位数。");
studentNo=stno;
name=nm;
}
void showInfo(){
System.out.println("学号:"+studentNo);
System.out.println("姓名:"+name);
}
}
public class Exceptions2{
public static void main(String[] args){
stt st=new stt();
try{
st.setStudent("4324","张三");
}catch(numException e){
System.out.println(e.getReason());
}
st.showInfo();
}
}
class numException extends Exception{
private String reason;
public numException(String r){
reason=r;
}
public String getReason(){
return(reason);
}
}
/*
学号位数不对,应该是9位数。
学号:null
姓名:null
*/
//在setStdudent头部加了throw numException()短语,说明本方法可能抛出异常。当在Main方法中
//爸setStudent放在try语句块中,并随后对其进行异常捕获处理。
//方法调用时的异常处理
/*public class Exceptions2 {
public static void main(String args[]){
int x[]={2,5,9};
try{
div d=new div();
d.meth();
x[3]=100;
}catch(ArithmeticException e){
System.out.println("1");
}catch(RuntimeException e){
System.out.println("2");
}catch(Exception e)
{
System.out.println("3");
}
}
}
class div{
void d(int a,int b){
int s=0;
s=a/b;
System.out.println("商:"+s);
}
void meth()
{
d(18,2);
d(3,0);
}
}
//
/*
商:9
1
在方法d()中并没有捕获和处理异常,因此该异常向他的调用者方法meth()抛出,在main中Udine异常进行捕获
*/
class stt{
private String studentNo,name;
void setStudent(String stno,String nm) throws numException{
if(stno.length()!=9)
throw new numException("学号位数不对,应该是9位数。");
studentNo=stno;
name=nm;
}
void showInfo(){
System.out.println("学号:"+studentNo);
System.out.println("姓名:"+name);
}
}
public class Exceptions2{
public static void main(String[] args){
stt st=new stt();
try{
st.setStudent("4324","张三");
}catch(numException e){
System.out.println(e.getReason());
}
st.showInfo();
}
}
class numException extends Exception{
private String reason;
public numException(String r){
reason=r;
}
public String getReason(){
return(reason);
}
}
/*
学号位数不对,应该是9位数。
学号:null
姓名:null
*/
//在setStdudent头部加了throw numException()短语,说明本方法可能抛出异常。当在Main方法中
//爸setStudent放在try语句块中,并随后对其进行异常捕获处理。