Java notes--exception details and handling

Source: Internet
Author: User
Tags instance method terminates throw exception throwable

First, the concept of anomalies

The Throwable class is a superclass of all errors or exceptions in Java.


1. Only if the object is an instance of this class (or its subclasses) can it be thrown through a Java virtual machine or a Java throw statement.
2. Only this class or its subclasses can be a parameter type in a catch clause.
3. There are two direct sub-categories:Error and exception
error--A serious problem that the application should not handle capture, often indicating system-level errors, such as memory overflow
exception--It is a design or implementation problem that the program needs to be captured and the exception that needs to be handled.
Exception are divided into two categories:RuntimeException and Checkedexception
runtimeexception--run-time exceptions, caused by programmer errors, do not require capture processing, directly by
The virtual machine takes over, the layer is thrown, the log is logged, and the programmer should try to avoid this kind of exception.
checkedexception--General exceptions, which require catch, such as IO Exceptions and SQL exceptions.

Note: error is not a programmer's concern, system-level errors
RuntimeException requires programmers to be careful with logic and coding, to avoid this kind of error as much as possible.
Checkedexception need for capture processing


--Support knowledge sharing, reprint please mark the address "http://www.cnblogs.com/XHJT/p/3927577.html"--and Woo Blog park, thank you ~~--

Second, the common runtimeexception anomaly:

1.ArithmeticExceptionArithmetic exception--The most common divisor is 0

2.ArrayindexOutOfBoundsExceptionArray subscript out-of-bounds exception, but when traversing an array, use foreach or arrarylist to avoid this exception.

3.ClassCastExceptionCast exception

4.ClassNotFoundExceptionThe specified class exception is not found, and such exceptions often occur in the following cases.
Example: The Forname method in class
Findsystemclass methods in the ClassLoader class
LoadClass methods in the ClassLoader class

5.NullPointExceptionA null pointer exception that is thrown when an application attempts to use null where the object is needed:
Example: Calling an instance method of a Null object
accessing or modifying fields of a null object
Use NULL as an array to get its length
Use NULL as an array to access or modify its element values
Throws null as a Throwable value
To avoid such exceptions, you can initialize a reference type variable when you define it, or use this variable to determine whether it is null.

6.arraystoreexceptionArray stored value exception-This exception is thrown when the element type is inconsistent, but this exception is not thrown if the array reference type is object.


Iii. Other common anomalies

1.IllegalAccessExcetionIllegal access exception--is when an application attempts to create a reflexive instance (not an array), set or get a field,
Or call a method, but the currently executing method cannot access the definition of the specified class, field, method, or construction method
Throws an exception.
This exception is most commonly used to set the value of a private domain with reflection under the security manager. At this point you must use Setaccessible () to modify
The visibility of the. In general, try to avoid using reflection to access private domains.

2.FileNotFoundExceptionThe file did not find an exception--the exception that was thrown when attempting to open a file that specifies a path name that indicates a failure. Does not exist with the specified path
The FileInputStream, FileOutputStream, and Readomaccessfile constructor methods are thrown when the file is named.
This exception is thrown if the file exists and is inaccessible for other reasons. such as opening a read-only file for writing.
To avoid such exceptions, you can first determine whether the file exists by using the exists () method in the file class. You can also use the file selector to
The actionable files are listed.

3.SqlExceptionDatabase exception--provides exceptions to database access errors or other error messages. This exception allows you to know:
A. A string describing the error;
B. " SQLstate "String that adheres to the Xopen ssqlstate Convention or sql:2003 Convention
C. Integer error codes that are specific to each vendor.
D. Links to the next exception
E. Causal relationship, can identify any cause of this SqlException

Iv. Handling of anomalies

Throw
Use the Throw keyword to throw an exception in the method body. This exception can make the system predefined exceptions, but also user-defined exceptions;
The throw always appears in the function body and is used to throw a specific exception. The program terminates immediately after the throw statement, and the statement behind it
Not be able to, and then in all the try blocks that contain it (possibly in the upper call function) look out for the catch that contains it
Try block for sentence:

throw exception object;
the exception to be thrown must be applied in the method body.

throws:
An exception may be thrown using the throws keyword, which can either make the system predefined exceptions or user-defined exceptions;
Throws always appears in a function header to indicate the various exceptions that the member function might throw. For most exception
Subclasses, the Java compiler forces you to declare the type of exception thrown in a member function. If the type of the exception is
Error or runtimeexception, or their subclasses, this rule does not work because this is in the normal part of the program
is not expected to appear. If you want to explicitly throw a runtimeexception, you must use the throws statement to declare its
Type.

[< modifier >]< return value type >< method name > ([< parameter list;]) [throws< exception class;]
Note: Exception classes can be declared multiple, separated by commas.


The difference between throw and throws:
1. The former is used in the method body, is a statement that throws a specific exception, which is used when declaring a method, is a method that declares an exception that may be thrown.
2. The former cannot be used alone, either with the try-catch-finally or with the throws, which can be used alone.
3. Use the former, you must throw an exception, using the latter may throw an exception
4. The program terminates immediately after the throw statement, the statement following it is not executed, and then in all the try blocks that contain it (possibly in the upper call function) from the Inside Out
Find the try block that contains the catch clause that matches it.

to add a hint message for a scheduled exception:

For system-predefined exceptions, there are generally at least two constructors, i.e.parametric structures and non-parametric structures。 Programmers can use the method to construct a parameter to add a hint message.


code Example:

 Packagecom.xhj.exception;/*** To add a hint to the exception: * *@authorXiehejun **/ Public classAddexceptionmessage { Public Static voidthrowexception () {Throw NewUnsupportedoperationexception ("No Data"); }     Public Static voidMain (string[] args) {Try{addexceptionmessage.throwexception (); } Catch(Exception e) {System.out.println (E.getmessage ()); }    }}

user-defined exceptions:


Although Java itself defines the exception class is already very rich complete, but in the actual application, the demand is always changeable.
Programmers can customize exception classes to meet development needs when demand is not available in Java-predefined exception classes.

To write a custom exception class is simple, you only need to inherit the exception class or its subclasses , and then implement its construction method.
Public class MyException extends exception{}

code Example:

 Packagecom.xhj.exception;/*** Custom Exceptions * *@authorXiehejun **/ Public classMydefinedexceptionextendsException { Publicmydefinedexception (String message) {Super(message); }     Public Static voidMain (string[] args)throwsmydefinedexception {string[] str= {"1", "2", "3", "4", "5", "6" };  for(String string:str) {if(String.Equals ("6")) {                Throw NewMydefinedexception ("This data cannot be greater than its byte length!") "); }        }            }}

Catching Exceptions:

When an exception is encountered, we generally have two solutions: one of course is to throw an exception , and the other is to catch the exception .
Throwing an exception is a very simple behavior, but this simple behavior will allow the program to exit directly. And in actual demand,
Not all exceptions can be thrown, because anyway, we always have to keep the program running, otherwise there is no point.

The catch of the exception is done through the try--catch--finally statement block:


1.try is an indispensable statement block, which is mainly used to place statements that may appear abnormal;
2.catch and finally must have at least one 1 with try matching;
The 3.catch block is used to place the processing statement after the exception occurs;
The 4.finally is placed in a statement that executes regardless of whether an exception occurs.

Note: Capturing exceptions consumes very high memory, so the statements in the try block should be as few as possible.

try--catch--finally Order of execution:

Instance code:

 Packagecom.xhj.exception;/*** Recognize the order of execution of try--catch--finally * *@authorXiehejun **/ Public classExecuteexceptionshort { Public Static voidMain (string[] args) {string[] STRs=NewString[5]; Try {            inti =strs.length; System.out.println ("----into the try code block----"); System.out.println ("String array size is:" +i); String Str= "I am an ugly duckling!" "; strs[5] =str; System.out.println ("Strs[5] =" + strs[5]); System.out.println ("----Leave the Try code block----"); } Catch(Exception e) {System.out.println ("----into the catch code block----"); System.out.println ("Exception is:" +e.tostring ()); System.out.println ("----Leave the Catch code block----"); } finally{System.out.println ("----into the finally code block----"); strs[4] = "I am the beautiful white Swan"; System.out.println (strs[4]); System.out.println ("----Leave the Finally code block----"); }    }}


Note: The try--catch--finally statement block captures multiple exceptions, but it is important to note the order in which multiple catches are executed when multiple exceptions are caught.
The exceptions to be caught must be arranged from small to large. Of course, can also be directly through all the exception of the parent class exception, to simple processing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.