异常处理

1.5个关键字

   try,catch,finally,throw,throws
  try 执行可能产生异常的代码
  catch捕获异常
  finally无论是否有异常,代码都能被执行
  throws:声明方法可能要抛出的各种异常
  throw:手动抛出异常
 
         Scanner input= new Scanner (System.in);
          try{
             System. out.println("请输入被除数:" );
              int num1=input.nextInt();
             System. out.println("请输入除数:" );
              int num2=input.nextInt();
             System. out.println(num1/num2);
         } catch(InputMismatchException e){
             System. out.println("输入了非法数字" +e.getMessage());
             e.printStackTrace(); //在程序测试时,显示完成的异常信息
         } catch(ArithmeticException e){
             System. out.println("除数不能为零" +e.getMessage());
             e.printStackTrace();
         } catch(Exception e){
             System. out.println(e.getMessage());
             e.printStackTrace();
         } finally{
              //资源的释放
             
         }   
//       System.out.println("请输入被除数:");
//        int num1=1;
//        int num2=1;
//       if(input.hasNextInt()){
//           num1=input.nextInt();
//       }else{
//           System.out.println("请输入整数!");
//           System.exit(0);
//           
//       }
//       System.out.println("请输入除数:");
//       if(input.hasNextInt()){
//           num2=input.nextInt();
//           if(num2==0){
//               System.out.println("请输入非零数字");
//               System.exit(0);
//           }
//       }else{
//           System.out.println("请输入整数!");
//       }
//       
//       System.out.println(num1/num2);
        System. out.println("感谢使用使本程序!" );         
    }
2.异常分类
(1)常见异常类型
      运行时异常(RuntimeException)与检查型异常
  注意事项:
  • 尽量减少try块的体积 
  • 既然捕获了异常,就要对它进行适当的处理。不要捕获后又把它丢弃,不予理睬
  • 在catch块中尽可能指定具体的异常类型,必要时可用多个catch,不要试图处理所有的异常
  • 在异常处理时提供适量的异常错误信息,便于阅读与理解。 
 
  
      e.getMessage()//获取信息
  e.printStackTrace()//打印堆栈
 
public class CopyDemoException extends RuntimeException {
    public CopyDemoException(){
         
    }
    public CopyDemoException(String message){
          super(message);
    }
    public CopyDemoException(Throwable throwable){
          super(throwable);
    }
    public CopyDemoException(String message,Throwable throwable){
          super(message,throwable);
    }
}
 /**
     * 实现文件拷贝
     * @param file 源文件
     * @param dir 目标目录
     * @throws CopyDemoException  用户自己写的异常类
     */
    //第一种异常处理方法
//  public static void copy(File file,File dir) throws
//  CopyDemoException{
//       if(!file.exists()){
//           throw new CopyDemoException("文件不存在!");//其中CopyDemoException是用户自己写得类
//       }
//       if(!dir.exists()){
//           throw new CopyDemoException("目录不存在!");
//       }
//       if(file.isFile()){
//           throw new CopyDemoException("不是文件!");
//       }
//       String src=file.getName();
//       File target=new File( dir,src );
//       
//       byte[] data=new byte[8*1024];
//        int c=0;
//       BufferedInputStream bis=null;
//       BufferedOutputStream bos=null;
//       try {
//            bis=new BufferedInputStream(new FileInputStream(file));
//            bos=new BufferedOutputStream(new FileOutputStream(target));
//           while((c=bis.read(data))!=-1){
//               bos.write(data,0,c);
//           }
//           //file1.delete();
//       } catch (IOException e) {
//           throw new CopyDemoException("文件拷贝错误!");
//       }finally{
//           try {
//               bis.close();
//               bos.flush();
//               bos.close();
//           } catch (IOException e) {
//               // TODO Auto-generated catch block
//               throw new CopyDemoException("文件流关闭错误!");
//           }
//           
//       }
//       
//  }
    
    //第二种异常处理方法,再在主函数中根据返回值,提示相应的信息
    
//  public static int copy(File file,File dir) throws
//  CopyDemoException{
//       if(!file.exists()){
//           return -1;
//       }
//       if(!dir.exists()){
//           return -2;
//       }
//       if(file.isFile()){
//           return -3;
//       }
//       String src=file.getName();
//       File target=new File( dir,src );
//       
//       byte[] data=new byte[8*1024];
//        int c=0;
//       BufferedInputStream bis=null;
//       BufferedOutputStream bos=null;
//       try {
//            bis=new BufferedInputStream(new FileInputStream(file));
//            bos=new BufferedOutputStream(new FileOutputStream(target));
//           while((c=bis.read(data))!=-1){
//               bos.write(data,0,c);
//           }
//           
//       } catch (IOException e) {
//           return -4;
//       }finally{
//           try {
//               bis.close();
//               bos.flush();
//               bos.close();
//           } catch (IOException e) {
//               // TODO Auto-generated catch block
//               return -5;
//           }
//           
//       }
//       return 1;
//  }
    
    //第三种异常处理方法
    public static void copy(File file,File dir) throws IOException{
          if(!file.exists()){
             System. out.println("文件不存在!" );
         }
          if(!dir.exists()){
             System. out.println("目录不存在!" );
         }
          if(file.isFile()){
             System. out.println("不是文件!" );
         }
         String src=file.getName();
         File target= new File(dir,src);
         
          byte[] data=new byte[8*1024];
          int c=0;
         BufferedInputStream bis= null;
         BufferedOutputStream bos=null;
         bis= new BufferedInputStream(new FileInputStream(file));
          bos=new BufferedOutputStream( new FileOutputStream(target));
          while((c=bis.read(data))!=-1){
              bos.write(data,0,c);
           }
          bis.close();
          bos.flush();
          bos.close();     
             
         }
         
注解: return的用法 
return 语句总是用在方法中,有两个作用,一个是返回方法指定类型的值(这个值总是确定的),另一个是结束方法的执行(仅一个return语句)。 3.日志文件
(1)日志jar包的导入
(2)Logger的使用
debug,info,warn,error(等级由低到高)
程序: 
private static Logger logger =Logger.getLogger(FileUtil.class);
//FileUtil是当前类的类名
logger .debug(e.getMessage());
logger .info(e.getMessage());
logger .warn(e.getMessage());
logger .error(e.getMessage());
配置文件:
log4j.rootLogger=error, logfile,stdout  //输出设备,
 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender//控制台
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
 
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=mylog.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern= %d{yyyy -MM-dd HH:mm:ss} %l %F %p %m%n
%d:日期  %l:代表产生异常的行标,%F:文件 %n:换行
注释:(1)程序中用logger .debug(e.getMessage());
      配置文件:log4j.rootLogger=error, logfile,stdout 中的error必须改为    debug
      (2)程序中用logger .error(e.getMessage());
      配置文件:log4j.rootLogger=error, logfile,stdout 中的error可以改为debug,info,warn,error
 即程序中出现的报错函数,其配置文件中报错函数的等级一定要低于它。
原文地址:https://www.cnblogs.com/langdon/p/4415414.html