Java中 try--catch-- finally、throw、throws 的用法

时间:2023-03-09 20:49:45
Java中 try--catch-- finally、throw、throws 的用法

一、try {..} catch {..}finally {..}用法

try {
  执行的代码,其中可能有异常。一旦发现异常,则立即跳到catch执行。否则不会执行catch里面的内容
} catch (Exception e) {
  除非try里面执行代码发生了异常,否则这里的代码不会执行
}

finally {
  不管什么情况都会执行,包括try catch 里面用了return ,可以理解为只要执行了try或者catch,就一定会执行 finally
}

看下面题目对比:

 public class test1 {
public static String output="";
public static void foo(int i) {
try {
if(i==1) //throw new Exception("i不能为1");
output+="A";
} catch (Exception e) {
System.out.println(e.getMessage());
output+="M";
return;
}finally {
output+="C";
}
output+="G"; }
public static void main(String[] args) {
foo(0);
foo(1);
System.out.println(output);
}
}

结果为:

CGACG

 public class test1 {
public static String output="";
public static void foo(int i) {
try { } catch (Exception e) {
// TODO: handle exception
}finally { }
try {
if(i==1) throw new Exception("i不能为1");
output+="A";
} catch (Exception e) {
System.out.println(e.getMessage());
output+="M";
return;
}finally {
output+="C";
}
output+="G"; }
public static void main(String[] args) {
foo(0);
foo(1);
System.out.println(output);
} }

结果为:

i不能为1
ACGMC

二、throw和throws的区别

   throws:用于声明异常,例如,如果一个方法里面不想有任何的异常处理,则在没有任何代码进行异常处理的时候,必须对这个方法进行声明有可能产生的所有异常(其实就是,不想自己处理,那就交给别人吧,告诉别人我会出现什么异常,报自己的错,让别人处理去吧)。格式是:方法名(参数)throws 异常类1,异常类2,.....

 class Math{
public int div(int i,int j) throws Exception{
int t=i/j;
return t;
}
} public class ThrowsDemo {
public static void main(String args[]) throws Exception{
Math m=new Math();
System.out.println("出发操作:"+m.div(10,2));
}
}

  throw:就是自己进行异常处理,处理的时候有两种方式,要么自己捕获异常(也就是try catch进行捕捉),要么声明抛出一个异常(就是throws 异常~~)。

  注意:

    throw一旦进入被执行,程序立即会转入异常处理阶段,后面的语句就不再执行,而且所在的方法不再返回有意义的值!

public class TestThrow
{
public static void main(String[] args)
{
try
{
//调用带throws声明的方法,必须显式捕获该异常
//否则,必须在main方法中再次声明抛出
throwChecked(-3);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
//调用抛出Runtime异常的方法既可以显式捕获该异常,
//也可不理会该异常
throwRuntime(3);
}
public static void throwChecked(int a)throws Exception
{
if (a > 0)
{
//自行抛出Exception异常
//该代码必须处于try块里,或处于带throws声明的方法中
throw new Exception("a的值大于0,不符合要求");
}
}
public static void throwRuntime(int a)
{
if (a > 0)
{
//自行抛出RuntimeException异常,既可以显式捕获该异常
//也可完全不理会该异常,把该异常交给该方法调用者处理
throw new RuntimeException("a的值大于0,不符合要求");
}
}
}