标签:
public static int f(int n){ try{ int r =n *n ; return r ; } finally{ if(n ==2) return 6; } }
该语句当n=2时,返回6。
△try finally语句中,finally语句中如果关闭抛出了异常,那么后抛出的异常将会把刚抛出的异常给覆盖
class XyyException extends Exception{ public XyyException(String s ){ super(s ); } } class HlhException extends Exception{ public HlhException(String s ){ super(s ); } } public class Demo { public static void main(String[] args) throws XyyException, HlhException { f(); } public static void f() throws XyyException, HlhException { int x =2; try{ x= x*2; throw new XyyException("try"); } finally{ if(x ==4){ throw new HlhException("finally"); } } } }
Exception in thread "main" string.Demo.HlhException: finally at string.Demo.Demo.f( Demo.java:26) at string.Demo.Demo.main( Demo.java:15)
public static int f(){ int x=10; try{ System.out.println(12/0); return x; } catch(Exception e) { x=20; return x; } finally { x=30; if(x==30) return x; } }
这个代码finally会将return30,因为finally中的return会将catch中的return覆盖,而如果没有return x,则该方法返回20,因为x仅仅赋值,但是返回的此时已经确定好了值.即在finally语句在return执行后返回前执行。
import java.util.*; public class FinallyTest6 { public static void main(String[] args) { System.out.println(getMap().get("KEY").toString()); } public static Map<String, String> getMap() { Map<String, String> map = new HashMap<String, String>(); map.put("KEY", "INIT"); try { map.put("KEY", "TRY"); return map; } catch (Exception e) { map.put("KEY", "CATCH"); } finally { map.put("KEY", "FINALLY"); map = null; } return map; } }
这个代码运行结果是finally。因为在try中即返回了引用所指向的对象(即确定的是对象),随后对对象的操作都会改变返回值,但是在finally代码块的最后一句将引用指向空,对于对象不构成任何影响,原对象返回。
package io.project.one; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; public class Demo2 { public static void main(String[] args) { Logger logger=Logger. getLogger("io.project.one.Demo2"); logger.setLevel(Level. FINE); try { FileHandler fh= new FileHandler("MyLogger.txt" ); fh.setLevel(Level. FINE); fh.setFormatter( new MyFormatter()); logger.addHandler( fh); logger.fine( "进入main函数" ); int x =2; int y =3; add(x,y); logger.exiting( "io.project.one.Demo2", "main" ); } catch (Exception e ) { e.printStackTrace(); } } public static void add(int x, int y) { Logger logger=Logger. getLogger("io.project.one.Demo2"); logger.fine( "io.project.one.Demo2"); System. out.println("x+y" ); logger.fine( "io.project.one.Demo2"); } } class MyFormatter extends Formatter{ @Override public String format(LogRecord record ) { return "类别:" +record .getLevel()+"....信息:"+ record.getMessage(); } }
标签:
原文地址:http://www.cnblogs.com/hlhdidi/p/5595835.html