The difference between throws and Thrownew RuntimeException and Try-catch

Source: Internet
Author: User
Tags terminates throw exception try catch

1. Throws appears in the method function head, can be used alone, and throw appears in the function body, can not be used alone, throw or try-catch-finally statement supporting use, or with throws matching use.

2.throws is basically declaring that this method throws this type of exception so that other places call it when it knows to catch the exception. Throw is a specific action that throws an exception, so it is throwing an exception instance.

3. Throws indicates that there is a possibility of an exception that does not necessarily occur, that the throw throws an exception, and that the execution of the throw throws a certain exception;

4. The program terminates immediately after the throw statement, and the statement following it is not executed, and then in all the try blocks that contain it (possibly in the upper call function), look for a try block containing its matching catch clause from inside out.


Java exception handling is implemented by 5 keywords: try,catch,throw,throws,finally. The following are some of the key words that are explained in JB's online Help:
Throws:lists the exceptions a method Couldthrow.
Throw:transfers control of the method to Theexception handler.
Try:opening exception-handlingstatement.
Catch:captures theexception.
Finally:runs its code before terminating Theprogram.
Try Statement
The Try statement uses curly braces {} to specify a piece of code that might discard one or more exceptions.
Catch statement
The parameters of a catch statement are similar to the declaration of a method, including an exception type and an exception object. The exception type must be a subclass of the Throwable class, which indicates the exception type that the catch statement handles, and the exception object is generated and captured by the runtime system in the code block specified by the try, which contains the processing of the object, where the object's methods can be called.
A catch statement can have more than one exception that handles a different class. The Java Runtime system detects the exception type processed by each catch statement from top to bottom until a matching catch statement of the type is found. Here, a type match means that the exception type handled by the catch is exactly the same as the type of the generated exception object or its parent class, so the order of the catch statement should be from special to generic.
You can also use a catch statement to handle multiple exception types, where the exception type parameter should be the parent of these multiple exception types, and the exception handling type of the catch statement should be selected according to the specific situation in the program design.
Finally statement
In the code that is qualified by try, when an exception is discarded, subsequent code is not executed. You can specify a piece of code by using the finally statement. Regardless of whether the exception is discarded or not discarded in the block specified by try, and whether the exception type of the catch statement is consistent with the type of the exception being discarded, the code specified by finally is executed, providing a uniform exit. Cleanup of resources is usually possible in the finally statement. such as closing open files.
Throws statements
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 types of exceptions are error or runtimeexception, or their subclasses, this rule does not work because this is not expected in the normal part of the program. If you want to explicitly throw a runtimeexception, you must declare its type with the throws statement.
Throw statement
The throw always appears in the function body and is used to throw an exception. The program terminates immediately after the throw statement, and the statement following it is not executed, and then in all the try blocks that contain it (possibly in the upper call function), look for the try block containing the catch clause that matches it.
Class MyException extends exception{
String msg;
MyException (int age) {
Msg= "Age can is not positive!";
}
Public String toString () {
return msg;
}
}
Class age{
public void intage (int n) throwsmyexception{//
if (n<0| | N&GT;120) {
MyException e=new myexception (n);
Throw e; is a turn statement, throws an object instance, stops execution of the following code
}
if (n>=0) {
System.out.print ("reasonable age!");
}
}
public static void Main (String args[]) {
int a=-5;
Try {//try catch must have
Age-age = New Age ();
Age.intage (a);//Trigger exception
System.out.print ("Code after exception is thrown");//This code is not executed, the program has been turned
} catch (MyException ex) {
System.out.print (Ex.tostring ());
}
finally{//regardless of whether the exception type of the catch statement is consistent with the type of exception being thrown, the code specified by finally is executed, providing a uniform exit.
System.out.print ("Enter finally! ");
}
}
}
Result: Age is illegal! Enter finally!
Another example:
void Fun () throws Ioexception,sqlexception
{
...
}
This means that the fun method may throw two exceptions, so when you call fun, you're ready to do it, like this.
Try
{
Fun ();
}catch (IOException e)
{
}catch (SQLException e)
{

}

Difference One:
Throw is a statement that throws an exception; throws is a method that throws an exception;
Throw syntax:throw< exception object >
In a method declaration, adding a throws clause indicates that the method throws an exception.
Throws syntax:[< modifier >]< return value type >< method name > ([< parameter list;]) [throws< exception class;]
Where: The exception class can declare multiple, separated by commas.
Difference Two:
Throws can be used alone, but throw cannot;
Difference Three:
The throw is either used with the try-catch-finally statement or used with the throws. However, throws can be used alone and then caught by the method that handles the exception.

Throws E1,e2,e3 just tells the program that this method might throw these exceptions, and the caller of the method might want to handle the exceptions. And these abnormal e1,e2,e3 may be produced by the function body.
And the throw is clear where this exception is to be thrown.
void DoA () throws Exception1, Exception3 {
try {
......
} catch (Exception1 e) {
Throw e;
} catch (Exception2 e) {
SYSTEM.OUT.PRINTLN ("error");
}
if (A! = b)
throw new Exception3 ("Custom Exception");
}
Code block ... may produce abnormal Exception1, Exception2, and Exception3.
If a Exception1 exception is generated, it is captured and then thrown by the caller of the method to do the processing;
If the Exception2 exception is generated, the method does its own processing (printing out the wrong words), so the method will not throw out the Exception2 exception, Voiddoa () throws Exception1, Excpetion3 inside of the Exception2 also do not have to write;
The Exception3 exception is an error in the logic of the method, the programmer has to handle the logic error in the case of throwing an exception Exception3, the caller also needs to handle.
The throw statement is used in the body of the method to indicate that an exception is thrown and handled by the statement in the method body
The throws statement is used after the method declaration to indicate that the exception is thrown, and is handled by the statement in the previous-level method that called the method
Throws primarily declares that this method throws this type of exception so that other places call it when it knows to catch the exception.
Throw is a specific action that throws an exception, so it is throwing an exception instance.
throws indicate which of you might be inclined to
Throw it, that's where you turn that tendency into reality.
While
1) The throws appears in the method function head, and the throw appears in the function body;
2) throws represents the possibility of an exception, which does not necessarily occur; throw throws an exception, and execution throws must throw some exception;
3) Both are negative ways of handling exceptions (the negativity here is not to say that this is not a good idea), just throw or possibly throw an exception, but not by the function to handle the exception, and the real handling exception is handled by the upper call of the function.

1. Exception mechanism
The exception mechanism is what the program does when an error occurs. Specifically, the exception mechanism provides a secure channel for program exits. When an error occurs, the process of executing the program changes, and the control of the program is transferred to the exception handler.

The traditional way of handling exceptions is that the function returns a special result to indicate an exception (usually this particular result is commonly called), and the program that invokes the function is responsible for examining and parsing the results returned by the function. This is a disadvantage: for example, the function return-1 represents an exception, but if the function does want to return 1 the correct value of the confusion, the readability is reduced, the program code and the code to deal with the exception of the father together, the call function of the program to parse the error, which requires the client programmer has a deep understanding of the library function.

Process of exception handling:

① encounters an error, the method ends immediately, does not return a value, and throws an exception object.

② The program that called the method does not continue, but instead searches for an exception handler that can handle the exception and executes the code in it.
2 Classification of exceptions
Classification of exceptions:
Inheritance structure for ① Exceptions: base classes inherit ioexception such as Throwable,error and exception inheritance throwable,runtimeexception and exception, The concrete runtimeexception inherits the RuntimeException.
②error and RuntimeException and their subclasses become unchecked exceptions (unchecked), and other exceptions become checked exceptions (checked).

Characteristics of each type of exception
Error system:
The error class system describes the internal errors and resource exhaustion scenarios in the Java operating system. Applications should not throw objects of this type (typically thrown by virtual machines). In the event of such an error, there is nothing else to do except to try to get the program safely out of the way. Therefore, in the program design, should pay more attention to the exception system.
The exception system includes runtimeexception systems and other non-runtimeexception systems:
The ①runtimeexception:runtimeexception system includes wrong type conversions, array cross-border access, and attempts to access null pointers and so on. The principle of dealing with runtimeexception is that if a runtimeexception occurs, it must be a programmer's fault. For example, you can avoid array out-of-bounds access exceptions by examining array subscripts and arrays boundaries.
② Other non-runtimeexception (IOException, etc.): Such exceptions are generally external errors, such as attempting to read data from the end of a file, which is not an error in the program itself, but an external error that occurs in the application environment.

differs from C + + exception classification:
It is inappropriate to runtimeexception this class name in ①java because any exception is present at run time. (Errors that occur at compile time are not exceptions, in other words, exceptions are to resolve errors that occur when the program runs).
The Logic_error in ②c++ is equivalent to RuntimeException in Java, and Runtime_error is equivalent to the exception of non-runtimeexception types in Java.

3 How to use exceptions
Declaring a method throws an exception
① syntax: throws (slightly)
② why declare a method to throw an exception?
Method throws an exception as important as the type of the method return value. If the method throws an exception and does not declare that the method throws an exception, the client programmer can call this method without writing the code that handles the exception. Then, in the event of an exception, there is no suitable exception controller to resolve the exception.
③ Why is the exception thrown must have been checked for exceptions?
RuntimeException and error can be generated in any code, they do not need to be shown by the programmer to throw, and in the event of an error, the corresponding exception will be automatically thrown. Just checking that the exception was thrown by the programmer is in two cases: the client programmer calls the library function that throws the exception (the exception to the library function is thrown by the library programmer), and the client programmer throws an exception using the throw statement himself. When encountering error, programmers are generally powerless; when encountering runtimeexception, there must be a logic error in the program, to modify the program (equivalent to a method of debugging); Only checked exceptions are the programmer's concern, and the program should and should only throw or handle checked exceptions.
Note: A subclass method that overrides a method of a parent class cannot throw more exceptions than the parent class method, so sometimes the method of the parent class is designed to declare an exception, but the code of the actual implementation method does not throw an exception, and the purpose is to make it easier for the subclass method to overwrite the parent class method when the exception can be thrown.

How to throw an exception
① syntax: throw (slightly)
What exception does ② throw? For an exception object, the really useful information is the exception object type, and the exception object itself is meaningless. For example, if the type of an exception object is ClassCastException, then the class name is the only useful information. So, when choosing what exception to throw, the key is to choose the class name of the exception that clearly describes the exception.
③ exception objects typically have two constructors: one is a parameterless constructor, and the other is a constructor with a string that acts as an extra description of the exception object, in addition to the type name.
④ Create your own exception: you need to create your own exception when the Java built-in exception does not explicitly describe the exception. It is important to note that the only useful information is the type name, so do not expend effort on the design of the exception class.

Catching exceptions
If an exception is not handled, then, for a non-GUI program, the program will be aborted and output exception information, for a graphical interface program will also output the exception information, but the program does not abort, but return with the error page.

      Syntax: try, catch, and finally (slightly), the controller module must be immediately behind the try block. If an exception is thrown, the exception control mechanism searches for the first controller that matches the type of the exception and then it enters that catch clause and considers the exception to be controlled. Once the catch clause ends, the search for the controller stops.
      Capturing multiple exceptions (note syntax and order of capture) (slightly)
     finally usage and exception handling flow (slightly)
      What does exception handling do? For Java, because of garbage collection, exception handling does not need to reclaim memory. But there are still some resources that need to be compiled by programmers, such as files, web connections, and pictures.
      Should I declare a method to throw an exception or catch an exception in a method? Principle: Catch and handle exceptions that know how to handle them, and which ones do not know how to handle them.
Throw exception again
① Why do you want to throw the exception again? In this level, only a subset of the content can be processed, and some processing needs to be done in a higher level environment, so the exception should be thrown again. This allows each level of the exception handler to handle the exceptions it can handle.
② Exception handling flow: Catch blocks corresponding to the same try block will be ignored, and the thrown exception will go to a higher level.

4 other questions about the exception
① excessive use of exceptions: first, it is convenient to use exceptions, so programmers are generally no longer willing to write code that handles errors, but simply throw an exception. This is not true, and for fully known errors, you should write code that handles this error, increasing the robustness of the program. In addition, the efficiency of the anomaly mechanism is poor.
② separates exceptions from common errors: for common, completely consistent errors, code that handles this error should be written to increase the robustness of the program. Exceptions are only required for externally indeterminate and predictable run-time errors.
③ the information contained in the exception object: In general, the only useful information for an exception object is type information. However, this string can also be used as additional information when using the exception string constructor. Calling the exception object's GetMessage (), toString (), or Printstacktrace () methods can get additional information about the exception object, the class name, and the call stack, respectively. And the latter contains a superset of the previous information.

The difference between throws and Thrownew RuntimeException and Try-catch

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.