Exceptions in Java

Source: Internet
Author: User
Tags getmessage throwable

Exceptions are errors that occur during the process of running a program, described in Java by classes, and objects to represent specific exceptions. Java distinguishes it as error and exception,error are errors that the program cannot handle, and exception is the error that the program can handle. Exception handling is for the robustness of the program.

The Thorwable class is a superclass of all exceptions and errors, with two subclasses of error and exception, respectively, representing errors and exceptions. The exception class Exception is divided into run-time exceptions (RuntimeException) and non-runtime exceptions, the two exceptions are very different, also known as non-detection exceptions (unchecked Exception) and detection exceptions (Checked Exception)

Here's a visual look at the difference between the two in code:

Check for exceptions:

As shown, the code cannot be compiled without processing an exception that exists on the red line. It must be throws or Try-catch:

As shown, the two exceptions are try-catch processed, and the code compiles normally. Then such exceptions (FileNotFoundException and IOException) are called check exceptions, also known as non-runtime exceptions, meaning that the exception should be processed before compiling, otherwise it cannot be compiled.

Non-check Exceptions:

As shown, there is a arrayindexoutofboundexception, this exception is compiled successfully, run the exception, as the name implies, the exception means that the array angle is out of bounds, because the exception is at run time exception, so this kind of exception is called run-time exception, or non-check exceptions. Similar anomalies are nullpointerexception and so on.

Custom Exceptions:

There are several exceptions, no matter what type, are throwable indirect subclasses, have been encapsulated, we directly use the line, but sometimes our system according to the requirements of a variety of anomalies, this time we need to customize the exception object. Custom exceptions, as well as encapsulation of exceptions, is to use a custom class to encapsulate the exception information, the class inherits exception, only need to make a copy of the parent class construction method, through super to pass information to the parameter. Let's look at how the structure of the parent class is implemented:

Exception:

Throwable:

It is obvious that when we customize the exception class, we use super to call the constructor of the class's parent class exception in the constructor method, pass in the parameter, call the constructor in the parent class Throwable with super in exception, and pass in the parameter. and assigns the argument value to the Detailmessage property of the class, gets the value in the GetMessage () method, so there is "myexception.getmessage ()" (as mentioned below) . It can be seen that this method is actually called the method in the Throwable class.

Suppose There is a requirement: for user-entered user names to be detected, if the user name is not "Zhang San", Throw our custom exception object MyException and print the exception information.

Custom Exception classes:

1  Public classMyExceptionextendsexception{2 3     Private Static Final LongSerialversionuid = 1041819209403514525L;4     5      Publicmyexception (String message) {6         Super(message);7     }8}

Controller layer:

1  Public class Usercontroller {2     Private New UserService (); 3     4      Public throws myexception {5         return Userservice.queryuser (Name,password); 6     }7 }

Service Layer:

1  Public class UserService {2     Private New Userdao (); 3      Public throws myexception {4         return Userdao.queryuser (Name,password); 5     }6 }

DAO Layer:

1  Public classUserdao {2 3      PublicUser Queryuser (string name, string password)throwsMyException {4         if(!" Zhang San. Equals (name)) {5             Throw NewMyException ("Password entered or user name is incorrect");6         }7 8User User =NewUser ();9 user.setusername (name);Ten User.setpassword (password); One  A         returnuser; -     } -}

Test:

1  Public classTest {2 3      Public Static voidMain (string[] args) {4Usercontroller Usercontroller =NewUsercontroller ();5         Try {6User user = Usercontroller.queryuser ("Zhang Dasan", "111");7 System.out.println (user);8}Catch(myexception myexception) {9 System.out.println (Myexception.getmessage ());Ten         } One  A     } -}

As shown in: Call the method Queryuser (string name,string password) in the controller in the test class to query the user, which internally calls the service layer's Queryuser (string name, String password) method, the method inside the service calls the Queryuser (String name,string Password) method of the DAO layer, and the method parameters are judged inside the DAO layer. If an exception occurs when the parameter satisfies a condition, throws the exception, and throws in the method declaration section, tells the object calling the method, the method may have an exception, you want to call it, you have to deal with it, as for the method of processing depends on the caller, or directly in the method declaration part throws thrown, To the next level, or Try-catch, then who is the current caller, call the DAO layer this method is the service layer, then the service layer is only throws, the exception continues to throw up, in the same way, the call service is the controller , the controller is also carried out throws, then in the test class test called the controller layer method, the Try-catch processing, to the possible exception of the code to try, if the hearing of the exception and catch caught by the exception object corresponding, Then it's handled, and the process here is simply printing exception information:

Exceptions in Java

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.