Java Exception Handling

Source: Internet
Author: User
Document directory
  • Setstacktrace
  • Printstacktrace
  • Fillinstacktrace
  • Getstacktrace

Java Exception Handling provides a language-level mechanism for handling runtime errors. Exception Handling mechanisms include exception systems and try statements for exception handling. Throw the throw statement of the custom exception object and declare the throws clause of the method to throw the exception. These functions allow the program not only to capture and handle exceptions, but also to actively throw exceptions and pass exceptions to calls.

Java. Lang. Object
Java. Lang. throwable
Java. Lang. Exception

Java. Lang. Object
Java. Lang. throwable
Java. Lang. Exception
Java. Lang. runtimeexception

RuntimeExceptionIs the superclass that may throw exceptions during the normal operation of the Java Virtual Machine.

Thrown but not captured during method executionRuntimeExceptionNo subclassthrowsClause.

ThrowableClass is the superclass of all errors or exceptions in Java. The Java virtual machine or JavathrowStatement throw. Similarly, only this class or one of its subclasses can becatchThe parameter type in the clause.

Two subclass instances,ErrorAndException, Usually used to indicate exceptions. Generally, these instances are newly created in the context of an exception and contain relevant information (such as stack trace data ).

========================================================== ========================================================== ==================

Setstacktrace
public void setStackTrace(StackTraceElement[] stackTrace)
Set getStackTrace()And printStackTrace()And stack trace elements output by related methods. This method is designed for RPC frameworks and other advanced systems and allows clients to override default stack traces, which are either created fillInStackTrace()Generated or deserialized when throwable is read from the serialized stream.

 

Parameters:
stackTrace-To do this ThrowableThe associated stack trace element. The specified array is copied by calling the method. After the method is returned, the changes in the specified array will not ThrowableStack trace.
Printstacktrace
public void printStackTrace(PrintWriter s)
Output The throwable and its tracing to the specified printwriter.

 

Parameters:
s-Used for output PrintWriter

Fillinstacktrace
public Throwable fillInStackTrace()
Fill in the exception stack trace. This method is available in ThrowableThe object information records the current status of the current thread stack frame.

 

Return Value:
This ThrowableInstance reference.
Getstacktrace
public StackTraceElement[] getStackTrace()
Provide programming access printStackTrace()Stack trace information. Returns an array of stack trace elements. Each element represents a stack frame. The zero element of the array (assuming that the data length is not zero) indicates the top of the stack, which is the last method call in the sequence. Generally, this is where the throwable is created and thrown. The last element of the array (assuming that the data length is non-zero) indicates the bottom of the stack, which is the first method call in the sequence.

Some virtual machines may omit one or more stack frames from the stack trace in some cases. In extreme cases, virtual machines without the throwable stack trace information can return a zero-length array from this method. In general, the array returned by this method will containPrintstacktraceAn element of each output frame.

 

Return Value:
An array of stack trace elements, indicating the stack trace associated with this throwable.

===============================================================================================

Running exceptions are subclasses of runtimeexception, which are described as follows:

1. Arithmetic exception: arithmeticexception

2. Null Object exception: nullpointexception

3. Type forced conversion exception: classcastexception

4. Negative array length exception negativearraysizeexception

5. array subscript out-of-bounds exception: arrayindexoutofboundsexception

6. numeric format exception: numberformatexception

An exception object is thrown, captured, and processed. The process of creating an exception-type object is called throw exception, and the process of obtaining the exception object is called catch exception. The process of performing corresponding operations on the exception object is called processing exception, the exception object is processed by the captured statement. Generally, these processes are completed by different methods or Java virtual machines.

=======================================================================================

package Exception;

Public class arrayaverage2 {
Public static double average (INT table [])
{
If (table! = NULL & table. length! = 0)
{
Double sum = 0;
For (INT I = 0; I <Table. length; I ++)
Sum + = table [I];
Return sum/table. length;
}
Return 0.0;
}
Public static double average (INT Table1 [], int Table2 [])
{
Int COUNT = 0;
If (Table1! = NULL & table1.length! = 0)
Count = table1.length;
If (table2! = NULL & table2.length! = 0)
Count + = table2.length;
If (count! = 0)
Return (average (Table1) * table1.length + average (table2) * table2.length)/count;
Else
Return 0.0;
}
Public static int [] tointarray (string STR [])
{
If (STR! = NULL & Str. length! = 0)
{
Int temp [] = new int [Str. Length];
Int COUNT = 0;
For (INT I = 0; I <Str. length; I ++)
Try
{
Temp [count] = integer. parseint (STR [I]);
Count ++;
}
Catch (numberformatexception E)
{
System. Out. println ("string" + STR [I] + "cannot be converted to an integer. The exception class is" + E. getclass (). getname ());
}
Int table [] = new int [count];
System. arraycopy (temp, 0, table, 0, count); // copy an array
Return table;
}
Return NULL;
}
Public static void print (INT table [])
{
If (table! = NULL)
{
System. Out. Print ("the array element is :");
For (INT I = 0; I <Table. length; I ++)
System. Out. Print ("" + Table [I]);

System. Out. println ();
}
}
Public static void main (string [] ARGs ){
Int X [] = {1, 2, 4 };
Int y [] = {};
System. Out. println ("average (x, y) =" + average (x, y ));

Y = tointarray (ARGs );
Print (y );
System. Out. println ("average (y) =" + average (y ));
}

}
========================================================================================

package Exception;

public class IllegalAgeException extends Exception{
 public IllegalAgeException(String s)
 {
  super(s);
 }
 public IllegalAgeException()
 {
  this("");
 }

}
package Exception;

Public class person3 {
Protected string name;
Protected int age;
Public person3 (string name, int age) throws illegalageexception
{
This. Set (name );
This. Set (AGE );
}
Public void set (INT age) throws illegalageexception
{
If (age> = 0 & age <= 100)
This. Age = age;
Else
Throw new illegalageexception ("" + age );
}
Public void set (string name)
{
If (name! = NULL | Name! = "")
This. Name = Name;
Else
This. Name = "the name is unknown ";
}
Public void print ()
{
System. Out. println (this. tostring ());
}
Public static void main (string [] ARGs ){
Person3 p1 = NULL;
Try
{
P1 = new person3 ("", 20 );
// Call the Declaration to throw an exception method, which must be written in the try statement; otherwise, the compilation fails.
P1.set (120 );
}
Catch (illegalageexception e) // catch custom exception classes, rather than exception classes
{
E. printstacktrace (); // displays the exception detection trace information.
}
Finally
{
P1.print (); // Display object information
}

 }

}

Related Article

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.