Java Foundation 10th Day

Source: Internet
Author: User
Tags finally block getmessage throw exception

Java Exception Exception
Exceptions refer to errors that occur at run time, syntax errors that occur during the compilation phase, and so on, which cannot be called exceptions.

Compile class exception

Must be processed to compile normally (class cannot find, Io exception, throws method is explicitly stated in API documentation, must be processed)

Run-time exception (RuntimeException)

This exception can be handled or not handled.

Workarounds for run-time exceptions

Encountered an error terminating the program's operation, that is, the exception is not processed
When the programmer is writing the program, it takes into account the error detection, the error message prompt, when thrown to the Java runtime Environment, the exception object is captured, processing.
To catch an exception object using the Try/catch statement

public class Exception1 {
public static void Main (string[] args) {
Int[] arr = {A-i};
try{
System.out.println (Arr[4]); Plus try Block
}catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Array Out of Bounds");
}
}
}
Try attempt: Place the statement where the exception might have occurred
Catch capture: When an exception in a try block occurs, an exception object is generated, holding the object to match the exception class in the catch block, executing the statement in the catch block if it matches the type in the catch, which means that the catch block can have more than one.

public class Exception2 {
public static void Main (string[] args) {
String str =null;
try{
System.out.println (Str.length ());
}catch (NullPointerException e) {
SYSTEM.OUT.PRINTLN ("null pointer");
}catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Unknown error");
}
}
}
As can be seen from the program, a try can be added after a number of catch blocks, for the try statement block in the exception of the exceptions to capture, of course, there can only be a catch block execution, from the logical view of execution, and switch branch statements very similar.

When an exception is caught, all parent exception blocks should be queued after the subclass exception catch block

Access exception information

The program needs to access information about the exception object in the catch block, which can be obtained by accessing the exception parameter after the catch block, and when the Java runtime decides to call a catch block to process the exception object, the exception object is assigned to the exception argument after the catch block (that is, the formal parameter of the exception type). The program can use this parameter to obtain information about the exception.

GetMessage (): Returns the detailed description of the exception
PRINTSTACKTRACWE (): Print out the trace stack information for the exception
Printstacktrace (PrintStream s): Outputs the exception's trace stack information to the specified output stream
Getstacktrace (): Returns the trace stack information for this exception

Import Java.io.FileInputStream; Guide Package
public class Exception3 {
public static void Main (string[] args) {
try{
FileInputStream fis = new FileInputStream ("AA");
}catch (Exception e) {
System.out.println (E.getmessage ()); Print exception information
E.printstacktrace (); Print trace Information
}
}
}
Compile-time exceptions (must be captured)

Import Java.io.FileInputStream;
public class Exception4 {
public static void Main (string[] args) {
FileInputStream in = null;
try{
in = new FileInputStream ("AA");
}catch (Exception e) {
E.printstacktrace ();
}
}
}
Finally recycling resources

Complete exception-handling structure

try{
Business Processing Statements
}catch (Exception 1 E1) {
Exception Handling Statements
}catch (Exception 2 E2) {
Exception Handling Statements
}
...
finally{
Resource Recycling Statements
}
Attention:

In an exception-handling mechanism, only the try block is required, that is, if there is no try block, then there is no subsequent catch and finally block, and the catch and finally appear at least one, and of course can occur simultaneously; finally is behind all catch blocks

Import Java.io.FileInputStream;
Import java.io.IOException;

public class Exception5 {
public static void Main (string[] args) {
FileInputStream FIS = null;
try{
FIS = new FileInputStream ("AA");
}catch (IOException i) {
SYSTEM.OUT.PRINTLN ("exception occurred");
}finally{
SYSTEM.OUT.PRINTLN ("Always execute");
}
}
}
Note: system.exit (1); exit Virtual Machine # # # #总结-Unless you call a method that exits a virtual machine in a try block, a catch block, the statements in the finally block are always executed regardless of what code is executed in the try block, catch block, and what happens. -In general, do not use return or throw in the finally block to cause the method to terminate the statement, once the use of a return or throw statement in the finally block, will result in a try block, the Return,throw statement in the catch block is invalidated.

public class Exception6 {
public static void Main (string[] args) {
int res = test ();
System.out.println (RES); Print result is 3
}
public static int test () {
try{
System.out.println (2/0);
return 1;
}catch (Exception e) {
return 2;
}finally{
return 3;
}
}
}
Checked anomaly and runtime anomaly system

Checked exception: Compile-time exception
Runtime exception: Run-time exception
There are two ways to handle checked exceptions:

The current method explicitly knows how to handle the exception, the program should use the Try/catch block to catch the exception, and then fix the exception in the corresponding catch block
The current method does not know how to handle the exception and should be thrown at the method declaration
Runtime exception Handling mode:

Runtime exceptions do not need to be explicitly thrown, and you can use Try/catch blocks if your savings need to catch runtime exceptions.

Throwing an exception using the throws declaration is a way of handling the exception

The current method does not know how to handle this type of exception, which should be handled by the caller at the top level, and if the main method does not know how to handle this type of exception, you can also use throws to continue the declaration throw, and leave the exception to the JVM for processing. The JVM handles exceptions by printing the trace stack information for the exception and terminating the program's operation.

Throws declaration of syntax format for throwing exceptions

Method signature + throws Exception1,exception2 ...
Once a method throws the exception using the throws keyword declaration, the program does not need to use the Try/catch block to catch the exception.

Import java.io.*;
public class Exception8 {
public static void Main (string[] args) throws exception{//continue to throw exceptions to the JVM for processing
Test ();
}
public static void Test () throws exception{//Throw exception
FileInputStream fis = new FileInputStream ("AA");
}
}
When defining a method, there is a limit to using the throws declaration to throw an exception

Method overrides, the subclass method declaration throws an exception type that is either a subclass of the exception type thrown by the parent class declaration or the same, the exception that the subclass declaration throws does not allow the exception that is thrown by the parent class method declaration to be large

Summarize

There are some inconvenient places to use checked anomalies

For checked exceptions, it must be shown to capture and handle the exception, or an explicit declaration throws the exception, which undoubtedly increases the complexity of the programming
If an checked exception is thrown explicitly in a method, it will cause the method signature to be coupled with the exception, and if the method overrides the method of the parent class, the exception thrown by the method will also be limited by the exception thrown by the overridden method
How to throw an exception yourself

If you throw an exception in the program, you need to use the throw statement

The first thing to do is to generate an exception class object with the following syntax:

IOException e = new IOException ();
Throw e;
Treatment of checked anomalies and runtime anomalies

If the throw statement throws an exception that is an checked exception, the throw statement either explicitly catches the exception in a try block, or is placed in a method with the throws declaration thrown, that is, the exception is given to the caller of the method to handle;
If the throw statement throws a runtime exception, the statement does not need to be placed in a try block, nor is it required to be placed in a method with a throws declaration;

Import java.io.IOException;
public class Exception9 {
public static void Main (string[] args) {
The called Checkedex method throws an exception, is a compile exception, must be captured with Try,catch, or continues to be declared on the invoked method.
try{
Checkedex ();
}catch (Exception e) {
E.printstacktrace ();
}
The called method throws a run-time exception that can be ignored at all and handled by the caller, where the caller is the Main method
Runtimeex ();
}
The exception thrown in the method is a compilation exception that must be handled: either in a try block or on a method declaration with a throw declaration
public static void Checkedex () throws ioexception{
throw new IOException ("checked Exception");
}
public static void Runtimeex () {
The exception thrown in the method is a run-time exception that can be handled or ignored
throw new NullPointerException ();
}
}
method to throw an exception to the flowchart (ioexception--compiler Exception) as an example



Custom exception Classes

When defining an exception class, you typically need to provide two construction methods, one that is parameterless, and one that is constructed with a string that acts as a description of the exception object, that is, the return value of the GetMessage method of the exception object.

The syntax for customizing an exception class is as follows

public class MyException extends exception{
Public myexception () {}//NULL parameter construction
Public MyException (string s) {//parameter constructed string as information passing
Super (s); Constructor method for calling parent class exception
}
}
Case Practice

/*
Write the application Ecmdef.java, receive the command line two parameters, the request cannot enter a negative number, calculates two divides.
Inconsistent with data type (numberformatexception)
Missing command line arguments (arrayindexoutofboundsexception
Except 0 (arithmeticexception)
and enter negative numbers (Ecdef custom exceptions) for exception handling.
The first kinds of exceptions, Java already have the corresponding exception class, but the last one on the input negative number of the exception, the system does not have such an exception definition, so, this exception should be our custom exception.
Tips:
(1) Define the exception method (ECM) in the main class (ECMDEF) to complete the two number division function.
(2) Use exception handling statements in the main () method to handle exception handling.
(3) in the program, customize the Exception Class (ECDEF) that corresponds to the input negative number.
(4) Runtime accept parameters Java Ecmdef 20 10
args[0]= "args[1]=" 10 "
(5) The static method of the Interger class parseint (String s) converts s to the corresponding int value.
such as int a=interger.parseint ("314"); a=314;
Review how to use the API documentation to view the methods of the integer class
*/
public class Exception11 {
public static void Main (string[] args) {
try{
int a = Integer.parseint (args[1]);
int b = Integer.parseint (args[2]);
int res = Dev (A, b);
System.out.println (RES);
}catch (NumberFormatException nfe) {
SYSTEM.OUT.PRINTLN ("Inconsistent data type");
}catch (ArrayIndexOutOfBoundsException a) {
SYSTEM.OUT.PRINTLN ("Missing command line arguments");
}catch (ArithmeticException ae) {
SYSTEM.OUT.PRINTLN ("Divisor cannot be 0");
}catch (myexception me) {
System.out.println (Me.getmessage ());
}
}
public static int dev (int a,int b) throws myexception{
if (a<0| | b<0) {
throw new MyException ("divisor cannot be negative");
}
return a/b;
}
}
Custom exception Classes
Class MyException extends exception{
Public myexception () {}
Public MyException (String s) {
Super (s);
}
}

Java Foundation 10th Day

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.