异常类基础知识

/*
异常类
异常:异常处理将会改变程序的控制流程,让程序有机会对错误作出处理。java中,用异常类Exception的相应子类创建一个异常对象,并等待处理。java中用try-catch语句处理异常。
try-catch:可能会出现的异常操作放在try语句部分。当try语句出现异常时,try语句立即结束执行,转向执行相应的catch语句部分,所以程序将发生异常后的处理放在catch部分。
格式:
try{

 ...//包含可能发生异常的语句

}
catch (ExceptionSubClass1 e) {}   //catch语句中的异常类都是Exception的某个子类,表明try语句部分可能发生的异常。
catch (ExceptionSubClass2 e) {}


*/

//Ex.  try-catch语句
/*public class  Exception_Class
{
 public static void main(String[] args)
 {
  int n=0,m=0,t=0;
  try{
  t=111111;
  m=Integer.parseInt("12sdf3");
  n=Integer.parseInt("99999");
  System.out.println("我没有机会输出!");
  }
  catch(Exception e){
  System.out.println("发生异常!");
  m=123;
  }
  System.out.println("n="+n+",m="+m+",t="+t);
 }
}
*/
//自定义异常类
class MyException extends Exception
{
 String message;
 MyException(int n){
  message=n+"不是正数";
 }
 public String getMessage(){
 return message;
 }
}
class A
{
 public void f(int n) throws MyException{
  if(n<0){
  MyException ex=new MyException(n);
  throw(ex);
  }
  double number=Math.sqrt(n);
  System.out.println(n+"的平方根:"+number);

 }
}

public class Exception_class
{
 public static void main(String args[]){
  A a=new A();
 try
 {
 a.f(16);
 a.f(-11111111);
 }
 
 catch (MyException e)
 {
 System.out.println(e.getMessage());

 }
}
 
}

你可能感兴趣的:(异常类基础知识)