Java异常处理

throws表示当前方法不处理异常,而是交给方法的调用出去处理;

throw表示直接抛出一个异常;

1public class Demo1 { 2 3 /** 4 * 把异常向外面抛 5 * @throws NumberFormatException 6 */ 7 public static void testThrows()throws NumberFormatException{ 8 String str="123a"; 9 int a=Integer.parseInt(str); 10 System.out.println(a); 11 } 12 13 public static void main(String[] args) { 14 try{ 15 testThrows(); 16 System.out.println("here"); 17 }catch(Exception e){ 18 System.out.println("我们在这里处理异常"); 19 e.printStackTrace(); 20 } 21 System.out.println("I'm here"); 22 } 23}

这里我们直接把异常抛出了。

运行输出:

1我们在这里处理异常 2java.lang.NumberFormatException: For input string: "123a" 3 at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 4 at java.lang.Integer.parseInt(Integer.java:580) 5 at java.lang.Integer.parseInt(Integer.java:615) 6 at com.java1234.chap04.sec03.Demo1.testThrows(Demo1.java:11) 7 at com.java1234.chap04.sec03.Demo1.main(Demo1.java:17) 8I'm here

throw表示直接抛出一个异常;

我们可以根据业务在代码任何地方抛出异常:

1package com.java1234.chap04.sec03; 2 3public class Demo2 { 4 5 public static void testThrow(int a) throws Exception{ 6 if(a==1){ 7 // 直接抛出一个异常类 8 throw new Exception("有异常"); 9 } 10 System.out.println(a); 11 } 12 13 public static void main(String[] args) { 14 try { 15 testThrow(1); 16 } catch (Exception e) { 17 // TODO Auto-generated catch block 18 e.printStackTrace(); 19 } 20 } 21}

运行输出:

1java.lang.Exception: 有异常 2 at com.java1234.chap04.sec03.Demo2.testThrow(Demo2.java:8) 3 at com.java1234.chap04.sec03.Demo2.main(Demo2.java:15)
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Java日期时间API系列31

  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前

Java8(5):使用 Optional 处理 null

Java8(5):使用Optional处理null写过Java程序的同学,一般都遇到过NullPointerException:)——为了不抛出这个异常,我们便会写如下的代码:UserusergetUserById(id);if(user!

03.Android崩溃Crash库之ExceptionHandler分析

目录总结00.异常处理几个常用api01.UncaughtExceptionHandler02.Java线程处理异常分析03.Android中线程处理异常分析04.为何使用setDefaultUncaughtExceptionHandler前沿上一篇整体介绍了crash崩溃