来自:https://www.rowkey.me/blog/2017/09/17/java-exception/
public void doNotCloseResourceInTry() {FileInputStream inputStream = null;try {File file = new File("./tmp.txt");inputStream = new FileInputStream(file);// use the inputStream to read a file// do NOT do thisinputStream.close();} catch (FileNotFoundException e) {log.error(e);} catch (IOException e) {log.error(e);}}
public void closeResourceInFinally() {FileInputStream inputStream = null;try {File file = new File("./tmp.txt");inputStream = new FileInputStream(file);// use the inputStream to read a file} catch (FileNotFoundException e) {log.error(e);} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {log.error(e);}}}}public void automaticallyCloseResource() {File file = new File("./tmp.txt");try (FileInputStream inputStream = new FileInputStream(file);) {// use the inputStream to read a file} catch (FileNotFoundException e) {log.error(e);} catch (IOException e) {log.error(e);}}
public void doNotDoThis() throws Exception {...}public void doThis() throws NumberFormatException {...}
/*** This method does something extremely useful ...** @param input* @throws MyBusinessException if ... happens*/public void doSomething(String input) throws MyBusinessException {...}
try {new Long("xyz");} catch (NumberFormatException e) {log.error(e);}
public void catchMostSpecificExceptionFirst() {try {doSomething("A message");} catch (NumberFormatException e) {log.error(e);} catch (IllegalArgumentException e) {log.error(e)}}
public void doNotCatchThrowable() {try {// do something} catch (Throwable t) {// don't do this!}}
public void doNotIgnoreExceptions() {try {// do something} catch (NumberFormatException e) {// this will never happen}}
public void logAnException() {try {// do something} catch (NumberFormatException e) {log.error("This should never happen: " + e);}}
try {new Long("xyz");} catch (NumberFormatException e) {log.error(e);throw e;}
17:44:28,945 ERROR TestExceptionHandling:65 - java.lang.NumberFormatException: For input string: "xyz"Exception in thread "main" java.lang.NumberFormatException: For input string: "xyz"at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)at java.lang.Long.parseLong(Long.java:589)at java.lang.Long.(Long.java:965)at com.stackify.example.TestExceptionHandling.logAndThrowException(TestExceptionHandling.java:63)at com.stackify.example.TestExceptionHandling.main(TestExceptionHandling.java:58)
public void wrapException(String input) throws MyBusinessException {try {// do something} catch (NumberFormatException e) {throw new MyBusinessException("A message that describes the error.", e);}}
public void wrapException(String input) throws MyBusinessException {try {// do something} catch (NumberFormatException e) {throw new MyBusinessException("A message that describes the error.", e);}}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69902700/viewspace-3140345/ ,如需转载,请注明出处,否则将追究法律责任。