Cover: Luo Xiaoxi

Translator: Pan Pan

Know the enemy and know yourself, and you can fight a hundred battles without danger of defeat.

preface

This article summarizes ten common questions about Java exceptions.

directory

  1. Unchecked (Checked) vs. Unchecked (Unchecked)

  2. Best practices for exception management

  3. Why can’t variables declared ina try block be referenced ina catch or finally?

  4. Why is Double. ParseDouble (null) not the same as integer.parseInt (null)?

  5. Runtime exceptions commonly used in Java

  6. Can we catch multiple exceptions in the same catch clause?

  7. Can a constructor throw an exception in Java?

  8. Throw an exception ina final code block

  9. Will finally be executed if a try statement has a return?

  10. Why do some developers ignore exceptions?

Unchecked (Checked) vs. Unchecked (Unchecked)

To put it simply, checking exceptions are usually detected at compile time, so we must either catch them in the method ahead of time, or declare them in the method header and throw them. For example, the dividend is 0, the null pointer, etc. Checking exceptions are especially important because they tell developers who call your interface how to anticipate and handle these exceptions in advance.

For example, IOException is a common check exception, while RuntimeException (RuntimeException) is a non-check exception. You may want to peruse this Java exception hierarchy diagram before reading the rest.

Best practices for exception management

If an exception can be handled correctly, it should be caught and handled; otherwise, it should be thrown.

Why can’t variables declared ina try block be referenced ina catch or finally?

If you look at the following code, String S declared in a try block cannot be referenced in a catch, this code will not pass at compile time.


try {
	File file = new File("path");
	FileInputStream fis = new FileInputStream(file);
	String s = "inside";
} catch (FileNotFoundException e) {
	e.printStackTrace();
	System.out.println(s);
}

Copy the code

The reason is that you don’t know where in the try block an exception will be thrown, and it’s quite possible that the exception will be thrown before the object is declared. For this particular example, this is true.

Why is Double. ParseDouble (null) not the same as integer.parseInt (null)?

They do throw different exceptions, but that’s a JDK problem, and there were different waves of developers working on both interfaces at the time, so we don’t have to worry about it.


Integer.parseInt(null); 
// throws java.lang.NumberFormatException: null 

Double.parseDouble(null); 
// throws java.lang.NullPointerException

Copy the code

Runtime exceptions commonly used in Java

Here are a few:

IllegalArgumentException ArrayIndexOutOfBoundsException

These exceptions are used in situations where a target object does not meet our expectations. For example, the following is used in an if statement:


if (obj == null) {
   throw new IllegalArgumentException("obj can not be null");

Copy the code

Can we catch multiple exceptions in the same catch clause?

The answer is yes, but if all of the exceptions caught in the same catch clause inherit directly or indirectly from the same parent, then you can only catch the parent in the catch clause.

// This was required before Java 7
catch (AException a) {
     logger.error(a);
     throw new MyException("a");
catch (BException b) {
     logger.error(b);
     throw new MyException("b");
}catch (CException c) {
     logger.error(c);
     throw new MyException("c");
}

In Java 7, you can catch all of these exceptions
catch(AException | BException | CException ex){
     logger.error(ex);
     throw new MyException(ex);
}

Copy the code

Supplementary notes: Is this actually, began in Java 7 support catch clause to capture multiple exceptions, multiple abnormal use XOR symbol (I) * * * * connection, abnormal occurrence is likely to be A | B, but it can’t appear at the same time, the equivalent of these anomalies can not be directly or indirectly inherited from the same parent class, because if AB inherit the same parent class, It will not be able to write A | B, this is principle of inheritance.

Can a constructor throw an exception in Java?

The answer is yes, the constructor is just a special method. Consider this example.

Throw an exception ina final code block

It is legal to write:


public static void main(String[] args) {
	File file1 = new File("path1");
	File file2 = new File("path2");
	try {
 
		FileInputStream fis = new FileInputStream(file1);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} finally {
		try {
			FileInputStream fis = new FileInputStream(file2);
		} catch(FileNotFoundException e) { e.printStackTrace(); }}}Copy the code

But for better code readability, you should wrap the try-catch block into a new method and then put the method call ina finally clause:


public static void main(String[] args) {
	File file1 = new File("path1");
	File file2 = new File("path2");
	try {
 
		FileInputStream fis = new FileInputStream(file1);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} finally {
        // Encapsulate methodmethodThrowException(); }}Copy the code

Will finally be executed if a try statement has a return?

The answer is yes.

The Finally block always executes when The try block exits

A finally block executes whenever a try block exists. This feature allows programmers to avoid using return, continue, or break keywords ina try statement while ignoring operations to close related resources.

Why do some developers ignore exceptions?

A lot of times you’ll see code like this. Catch exceptions and handle them as much as you can. I wonder why so many developers do this?


try{... }catch(Exception e) {
     e.printStackTrace();
}

Copy the code

Ignoring exceptions is an easy thing to do, and while it’s common, it’s not necessarily the right way to write it.

References:
  1. Unchecked exceptions in Java
  2. The root of Java exception class hierarchy
  3. Java exceptions related questions in stackoverflow

After translation, due to my limited understanding ability and knowledge width, there are mistakes in translation, please forgive me, welcome correction.

BIU ~ the article continues to update, wechat search “Pan Pan and his friends” the first time to read, there are surprises at any time. This article will be included on GitHub github.com/JavaWorld, hot technology, framework, surface, solution, we will be the most beautiful posture in the first time, welcome Star.