throw new RuntimeException(e)与e.printStackTrace( )的区别

【java知识点异常】throw new RuntimeException(e)与e.printStackTrace( )的区别

2018年04月29日 11:07:58 zq爱生活爱代码 阅读数:115

转载自:https://blog.csdn.net/xuzhuaaron1/article/details/73611404
e.printStackTrace( )是打印异常栈信息,而throw new RuntimeException(e)是把异常包在一个运行时异常中抛出。

我们常看见这种写法
try{
....

}catch(Exception e){
e.printStackTrace( );
throw new RuntimeException(e);
//throw new RuntimeException(e.getMessage());



}
这是处理没法进一步处理的异常的一般做法。try块中出现了一个异常,它被catch住了,我们首先要在标准输出上打印出异常但是如果没有throw这句,这个错误就静悄悄地被catch块吃掉了,程序会继续运行。可这个时候很可能你的程序的状态已经不对了,继续下去也没有什么意义,所以应该继续抛出这个异常。你当然可以写throw e;,但是这个e是一般的异常,如果这样抛出的话,你得在这个函数头上用throws来声明,比如:
public void abc() throws Exception
然后调用这个函数的函数也还得这么干,所以一般的处理是把e包装成运行时异常:new  RuntimeException(e),这样就不需要在函数头声明了。

但这只是一般的处理方法,在实际程序中不可不顾实际情况和需求生搬硬套。
 
e.printStackTrace();在实际开发时意义不大,因为部署以后不会有人看控制台,这句很多情况下会被记录日志的代码代替。 throw new RuntimeException就是要把异常继续抛出,要么由上层方法解决,要么会终止程序运行,比如这里,如果初始化都无法正确完成,再继续运行下去也没有必要了。至于说多打印一句话,还是因为在工具环境下,你比较关注控制台,实际部署环境,没人看控制台信息,都会去看日志中记录的异常信息。 有结束进程的作用。
try catch如果不写throw new RuntimeException 只是不执行本方法后面的代码,然后跳出本方法后继续执行其他方法,不会结束程序。 如果在其他应用中,还可以把异常抛给上层调用者来处理。
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
public synchronized String nextId() { long timestamp = timeGen(); //获取当前毫秒数 //如果服务器时间有问题(时钟后退) 报错。 if (timestamp < lastTimestamp) { throw new RuntimeException(String.format( "Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } //如果上次生成时间和当前时间相同,在同一毫秒内 if (lastTimestamp == timestamp) { //sequence自增,因为sequence只有12bit,所以和sequenceMask相与一下,去掉高位 sequence = (sequence + 1) & sequenceMask; //判断是否溢出,也就是每毫秒内超过4095,当为4096时,与sequenceMask相与,sequence就等于0 if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); //自旋等待到下一毫秒 } } else { sequence = 0L; //如果和上次生成时间不同,重置sequence,就是下一毫秒开始,sequence计数重新从0开始累加 } lastTimestamp = timestamp; long suffix = (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; String datePrefix = DateFormatUtils.format(timestamp, "yyyyMMddHHMMssSSS"); return datePrefix + suffix; } protected long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } protected long timeGen() { return System.currentTimeMillis(); } private byte getLastIP(){ byte lastip = 0; try{ InetAddress ip = InetAddress.getLocalHost(); byte[] ipByte = ip.getAddress(); lastip = ipByte[ipByte.length - 1]; } catch (UnknownHostException e) { e.printStackTrace(); } return lastip; }
public class FTPUtil { private FTPClient ftpClient=null; private boolean result = false; private FileInputStream fis; String ftpHost = "10.16.111.111"; String port = 21 String ftpUserName = "ftpuser11; String ftpPassword = "1234561"; /** * 登录服务器 * @param ftpInfo * @return * @throws IOException */ public FTPClient login() throws IOException { ftpClient = new FTPClient(); ftpClient.connect(ftpHost); boolean login = ftpClient.login(ftpUserName,ftpPassword); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } if(login){ System.out.println("ftp连接成功!"); }else{ System.out.println("ftp连接失败!"); } //ftpClient.setControlEncoding("GBK"); return ftpClient; } /** * 字符串作为文件上传指定目录 下 * @param content 源字符串 * @param uploadDir 上传目录 * @param ftpFileName 上传文件名称 * @throws Exception */ public void ftpUploadByText(String content ,String uploadDir,String ftpFileName) throws Exception{ try { ftpClient = this.login(); //创建目录 createDir(ftpClient,uploadDir); // 设置上传目录 这个也应该用配置文件读取 ftpClient.changeWorkingDirectory(uploadDir); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); String fileName = new String(ftpFileName.getBytes("GBK"),"iso-8859-1"); OutputStream os = ftpClient.storeFileStream(fileName); byte[] bytes = content.getBytes(); os.write(bytes); os.flush(); os.close(); } catch (Exception e) { ftpClient.disconnect(); ftpClient = null; e.printStackTrace(); throw e; }finally{ ftpClient.disconnect(); ftpClient = null; } } /** * 移动文件 * @param ftpInfo * @return * @throws Exception */ public boolean moveFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.moveFile(ftpClient, ftpInfo.getChangeWorkingDirectoryPath(), ftpInfo.getFilePath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 删除文件 * @param ftpInfo * @return * @throws Exception */ public boolean deleteFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.deleteByFolder(ftpClient, ftpInfo.getChangeWorkingDirectoryPath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 实现文件的移动,这里做的是一个文件夹下的所有内容移动到新的文件, * 如果要做指定文件移动,加个判断判断文件名 * 如果不需要移动,只是需要文件重命名,可以使用ftp.rename(oleName,newName) * @param ftp * @param oldPath * @param newPath * @return */ public boolean moveFile(FTPClient ftp,String oldPath,String newPath){ boolean flag = false; try { ftp.changeWorkingDirectory(oldPath); ftp.enterLocalPassiveMode(); //获取文件数组 FTPFile[] files = ftp.listFiles(); //新文件夹不存在则创建 if(!ftp.changeWorkingDirectory(newPath)){ ftp.makeDirectory(newPath); } //回到原有工作目录 ftp.changeWorkingDirectory(oldPath); for (FTPFile file : files) { if(file.isDirectory()) { moveFile(ftp,oldPath+file.getName()+"/" ,newPath+file.getName()+"/"); }else{ //转存目录 flag = ftp.rename(oldPath+new String(file.getName().getBytes("GBK"),"ISO-8859-1"), newPath+"/"+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } if(flag){ System.out.println(file.getName()+"移动成功"); }else{ System.out.println(file.getName()+"移动失败"); } } ftp.removeDirectory(new String(oldPath.getBytes("GBK"),"ISO-8859-1")); } catch (Exception e) { e.printStackTrace(); System.out.println("移动文件失败"); } return flag; } /** * 删除FTP上指定文件夹下文件及其子文件方法,添加了对中文目录的支持 * @param ftp FTPClient对象 * @param FtpFolder 需要删除的文件夹 * @return */ public boolean deleteByFolder(FTPClient ftp,String FtpFolder){ boolean flag = false; try { ftp.changeWorkingDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); ftp.enterLocalPassiveMode(); FTPFile[] files = ftp.listFiles(); for (FTPFile file : files) { //判断为文件则删除 if(file.isFile()){ ftp.deleteFile(FtpFolder+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } //判断是文件夹 if(file.isDirectory()){ String childPath = FtpFolder +file.getName()+ "/"; //递归删除子文件夹 deleteByFolder(ftp,childPath); } } //循环完成后删除文件夹 flag = ftp.removeDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); if(flag){ System.out.println(FtpFolder+"文件夹删除成功"); }else{ System.out.println(FtpFolder+"文件夹删除成功"); } } catch (Exception e) { e.printStackTrace(); System.out.println("删除失败"); } return flag; } /** * 创建目录 * @param createpath * @param sftp */ public void createDir(FTPClient ftpClient,String createpath) throws Exception { try { if(ftpClient.changeWorkingDirectory(createpath)) { return; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if(!ftpClient.changeWorkingDirectory(filePath.toString())) { ftpClient.makeDirectory(filePath.toString()); ftpClient.changeWorkingDirectory(filePath.toString()); } } ftpClient.changeWorkingDirectory(createpath); }catch (Exception e) { e.printStackTrace(); throw new Exception("创建路径错误:" + createpath); } } }
public class CategoryDaoImpl implements CategoryDao { @Override public void add(Category category){ try{ QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); String sql = "insert into category(id,name) values(?,?)"; Object params[] = {category.getId(), category.getName()}; runner.update(sql, params); } catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } } /* (non-Javadoc) * @see dao.impl.CategoryDao#find(java.lang.String) */ @Override public Category find(String id){ try { QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); String sql = "select * from category where id=?"; return (Category)runner.query(sql, id, new BeanHandler(Category.class)); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } /* (non-Javadoc) * @see dao.impl.CategoryDao#getAll() */ @Override public List<Category> getAll(){ try { QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); String sql = "select * from category"; return (List<Category>)runner.query(sql, new BeanListHandler(Category.class)); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } @Override public int delete(String id) { try { QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); //执行删除的sql runner.update("delete from category where id=?",id); } catch (SQLException e) { throw new RuntimeException(e);//抛出运行异常 } return 1;//删除成功返回1表示结束 } @Override public void update(Category record) { try{ QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); String sql = "update category set name=?,where id=? "; Object params[] = { record.getName(), record.getId()}; runner.update(sql, params); } catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } } }帮我加一下注释
05-31
``` public class CategoryDaoImpl implements CategoryDao { // 添加分类 @Override public void add(Category category){ try{ QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); // 创建QueryRunner对象 String sql = "insert into category(id,name) values(?,?)"; // SQL插入语句 Object params[] = {category.getId(), category.getName()}; // 插入参数 runner.update(sql, params); // 执行插入操作 } catch(Exception e){ e.printStackTrace(); // 打印异常信息 throw new RuntimeException(e); // 抛出运行时异常 } } // 根据分类ID查找分类信息 @Override public Category find(String id){ try { QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); // 创建QueryRunner对象 String sql = "select * from category where id=?"; // SQL查询语句 return (Category)runner.query(sql, id, new BeanHandler(Category.class)); // 执行查询并返回结果 } catch (SQLException e) { e.printStackTrace(); // 打印异常信息 throw new RuntimeException(e); // 抛出运行时异常 } } // 获取所有分类信息 @Override public List<Category> getAll(){ try { QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); // 创建QueryRunner对象 String sql = "select * from category"; // SQL查询语句 return (List<Category>)runner.query(sql, new BeanListHandler(Category.class)); // 执行查询并返回结果 } catch (SQLException e) { e.printStackTrace(); // 打印异常信息 throw new RuntimeException(e); // 抛出运行时异常 } } // 根据分类ID删除分类信息 @Override public int delete(String id) { try { QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); // 创建QueryRunner对象 runner.update("delete from category where id=?",id); // 执行删除的SQL语句 } catch (SQLException e) { throw new RuntimeException(e); // 抛出运行时异常 } return 1; // 删除成功返回1表示结束 } // 更新分类信息 @Override public void update(Category record) { try{ QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); // 创建QueryRunner对象 String sql = "update category set name=?,where id=? "; // SQL更新语句 Object params[] = { record.getName(), record.getId()}; // 更新参数 runner.update(sql, params); // 执行更新操作 } catch(Exception e){ e.printStackTrace(); // 打印异常信息 throw new RuntimeException(e); // 抛出运行时异常 } } } ``` 这段代码实现了对分类信息的增、删、改、查功能。其中,每个方法都调用了QueryRunner对象执行SQL语句,并返回结果或抛出异常。方法名和注释说明了各个方法的具体功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值