Java Core Technology (6): Abnormal

1. Handling errors

  The task of exception handling is to transfer control from the place where the error occurs to the error handler that can handle this situation.

  Several possible errors:

  • User input error
  • Device error
  • Physical limitations (storage)
  • Code error

1. Anomaly classification

Insert picture description here

  • RuntimeException : Wrong type conversion, array access out of bounds, or null pointer access.

  • IOException : trying to read data after the end of the file; trying to open a file that does not exist; trying to find a Class object based on a given string, and the class represented by this string does not exist.

  • Checked exception : IOException, the compiler will check whether an exception handler is provided for all checked exceptions.

  • Unchecked exceptions : Error and RuntimeException

2. Declare checked exception

  The method should declare all possible exceptions in its header.

	public f(String name) throws FileNotFoundException
	{
    
    
		……
	}

  This code indicates that this method will call the method based on the given String parameter, but it may also throw a FileNotFoundException. If this bad situation occurs, the method will not be successfully called, but instead throws a FileNotFoundException class object. If this method really throws such an exception object, the runtime system will start searching for the exception handler to know how to handle the FileNotFoundException object.

  • In short, a method must declare all checked exceptions that may be thrown, and unchecked exceptions are either uncontrollable (Error) or should be avoided (RuftimeException). In other words, there is no need to throw exceptions for Error and RuntimeException, but all possible IOException exceptions need to be considered.
  • If a method of the superclass is overridden in the subclass, the checked exception declared in the subclass method cannot be more general than the exception declared in the superclass method (that is, more specific exceptions can be thrown in the subclass method, Or don't throw any exceptions at all). In particular, if the superclass method does not throw any checked exception, the subclass cannot throw any checked exception, but must catch every checked exception in the method code.

3. How to throw an exception

  • Steps : find a suitable exception class, create an object of this class, and throw the object.
String readData(Scanner in)throws EOFException
{
    
    
	...
	while(...)
	{
    
    
		if(!in.hasNext())
		{
    
    
			if (n <len))
			{
    
    
				String gripe="Content-length:"+len+",Received:"+n;
				throw new EOFException(gripe);//抛出异常
			}
			
		}
		...
	}
	return s;
}

  Once the method throws an exception, the method cannot return to the caller. In other words, don't worry about the default values ​​or error codes that are returned.

4. Create an exception class

  All we need to do is define a class derived from Exception, or a class derived from a subclass of Exception. For example, define a class derived from IOException. Traditionally, the defined class should contain two constructors, one is the default constructor; the other is the constructor with detailed description information (the toString method of the super class Throwable will print out these detailed information, which is in debugging very useful).

Two, catch the exception

  If an exception is not caught anywhere when it occurs, the program will terminate execution and print out the exception information on the console, including the type of the exception and the contents of the stack.

  The following are two ways to handle exceptions:

  • The first: if you don't know how to handle the exception, pass the exception to the caller.
	String readData(Scanner in)throws EOFException
	{
    
    
		...
		while(...)
		{
    
    
			if(!in.hasNext())
			{
    
    
				if (n <len))
				{
    
    
					String gripe="Content-length:"+len+",Received:"+n;
					throw new EOFException(gripe);//抛出异常
				}
				
			}
			...
		}
		return s;
	}
  • The second type: if you know how to deal with it, you can deal with it yourself
	public void read(String filename)
	{
    
    
		try
		{
    
    
			InputStream in= new FileInputStream(filename));
			int b;
			while((b =in.read())!=-1)
			{
    
    
				process input
			}
		}
		catch (IOException exception)
		{
    
    
			exception.printStackTrace();
		}
	}

  Read the Java API documentation carefully to know what kind of exception each method may throw, and then decide whether to handle it yourself or add it to the throws list. For the latter case, there is no need to hesitate. It is better to hand the exception directly to a competent processor for processing than to suppress it.

  However, there are restrictions on the use of throws. As mentioned earlier: If you write a method that covers the superclass, and this method does not throw an exception, then this method must catch every checked exception that appears in the method code. It is not allowed to appear in the throws specifier of the subclass beyond the scope of the exception class listed in the superclass method.

1. Catch multiple exceptions

  By using multiple catch clauses:

	try
	{
    
    
		...
	}
	catch()
	{
    
    
		...
	}
	catch()
	{
    
    
		...
	}
	catch()
	{
    
    
		...
	}
	e.getMessage();//获得更详细的错误信息
	e.getClass().getName();//得到异常的实际类型

  Catch clauses with the same action can be combined, but there can be no subclass relationship between the exception types, and the exception variable is implicitly a final variable:

	try
	{
    
    
		...
	}
	catch(FileNotFoundException|UnknownHostException e)
	{
    
    
		...
	}
	catch()
	{
    
    
		...
	}
	catch()
	{
    
    
		...
	}

2. Throw the exception and the exception chain again

	try
	{
    
    
		...
	}
	catch(SQLException e)
	{
    
    
		Throwable se = new ServletException("database error"); 
		se.initCause(e); 
		throw se;
	}

  When an exception is caught, you can use the following statement to retrieve the original exception:

	Throwable e = se.getCause();

  Sometimes you may just want to log an exception and rethrow it without making any changes:

	try
	 {
    
    
	 }
	catch(Exception e)
	{
    
    
		logger.log(level,message,e); 
		throw e;
	}

3.finally clause

  When the code throws an exception, it will terminate the processing of the remaining code in the method and exit the execution of this method. If the method acquires some local resources, and only the method knows it, and if these resources must be recycled before exiting the method, a resource recycling problem will arise. Use the finally clause to solve this problem.

  Regardless of whether an exception is caught, the code in the finally clause is executed.

	try
	{
    
    
		...
	}
	catch()
	{
    
    
		...
	}
	finally
	{
    
    
		...
	}

  Warning: When the finally clause contains a return statement, there will be an unexpected result. Suppose the retur statement is used to exit from the try block. Before the method returns, the content of the finally clause will be executed. If there is also a return statement in the finally clause, this return value will overwrite the original return value.

4. Try statement with resources

	try(Scanner in= new Scanner(new FileInputStream"/usr/share/dict/words"),
	 Printwriter out = new PrintMriter("out.txt")))
	 {
    
    
		  while (in.hasNext())
		 {
    
    
		 	out.println(in.nextO.toUpperCase();
		 }
	 }

  No matter how the block exits, in and out will be closed.

5. Analyze stack trace elements

  See the API of Throwable interface for details.

Guess you like

Origin blog.csdn.net/Tracycoder/article/details/112363181