Java Base exception (Bi Xiangdong teacher)

Source: Internet
Author: User
Tags try catch

Exception: not normal. Some of the abnormal conditions that occurred during the run time. is an exception.
The origin of the exception. Program Run is always
Class Exceptiondemo
{
public static void Main (string[] args)
{
Int[] Arr=new int[2];
System.out.println (Arr[2])
}
}


The unusual situation has many minutes, all need to describe separately, means that the abnormal situation should have a system.
More than one anomaly with the generality of continuous upward extraction, it formed a system.
An exception also has a parent class. By looking at the API, you find that the exception system is:
Throwable
|--error a serious problem, typically thrown from the bottom of the JVM, usually does not require processing
You can modify the program directly.
|--exception is the ability to define a targeted approach to dealing with this situation,
There are two kinds of abnormal situations, one is the exception that can be solved, the other is the error of severity.
Whether it's error or exception, the suffix of their subclass name is the parent class name.
int []arr=new int (1024*1024*700);//outofmemoryerror;

The virtual machine allocates space in memory (the name information is available) the underlying space fails and throws the exception to the caller.
No more shipping after a problem occurs. Throws the problem to the caller's knowledge. Thrown to the virtual machine.
Who calls the main function to whom it is given. Default handling: Directly package the problem (name, information, location) to the caller. )

System.out.println (arr[2]);//new arrayindexoutofexception ();
The most important feature of this anomaly system is that the classes and objects in the system have parabolic properties.
The embodiment of the parabolic is that either the class or the object can be manipulated by throws or throw
Throws Operation class. The throw action object.
Typically:
Class Demo
{
int div (int a,int b) throws exception//one more identity
{

if (b<0) {
throw new Fushuexception ("error, do not allow divisor to be negative");
throw new Fushuexceptin (b);
}
if (b==0)//To manually throw an exception object, you must use the Throw keyword.
throw new ArithmeticException ("Finish, be 0 apart!") ")
return a/b;//new ArithmeticException ("by Zero")

}
}

Class Exceptiondemo
{
public static void Main (string[] args) throws exception///This bread is probably broken.
(A label.) )
{
Demo D=new demo ();//Create object.
try{
int X=d.div (4,0);
System.out.println ("x=" +x);
}
catch (Exception e)//variable of reference type. The variable is used to receive the thrown exception.

{
Exception e=new arithmeticexception ();
System.out.println ("Ah, abnormal!");
Call the method to go. (He is Zhang Kaidi, but his father is not Zhang Kaidi)

SYSTEM.OUT.PRINTLN ("message" +e.getmessage ());

System.out.println ("toString" +e.tostring ());

E.printstacktrace ();//print name, information, location.
}
Arithmeticexception:/by Zero; Call Div, he throws it here.
Default processing: Thrown to the JVM (that is, name, information, location package to the caller, all printed on the console; end
Program

System.out.println ("over");

}
}


An exception is handled:
Processing method:
1, the declaration is thrown. Tell the caller that there is a problem with the feature, and declare the issue to function with the throws keyword.
2, to capture. You can use the targeted snap block to complete the code.
try{
Code that needs to be instrumented
}
catch (Exception class variable)
{
Exception handling code
}
Finally
{
Code that is bound to be executed
}

The program will continue to execute down.

What is the difference between the throws throw keyword?
Throws used in functions, for function declaration exception, followed by the exception class, you can run out of multiple, as long as the comma separated
Just open it.
Throw can only be used within the function, to throw the exception object, additional features, once executed, you can end the function.

Custom exceptions: For common anomalies, Java has a corresponding description. For example, the corner mark crosses
or null pointers, and so on. Java does not give a specific question about a custom program
Describe. This is a question that needs to be described in terms of object-oriented thinking, like an anomaly.
Encapsulate it as an object.
Define the way;
1, define the way: Define a class to describe the problem.
2, you must let this class inherit the exception class, with the ability to be parabolic.
Class Fushuexception extends Exception
{
private int num;
Fushuexception ()
{
Super ();
}
Fushuexception (String message)
{
Super (message);
}
fushuexception (int num)
{
This.num=num;
}
public int Getnum ()
{
return num;
}
}
Details of the exception:
1, define the function, internal function because of the problem of incoming parameter, cause the problem of function.
At this point to solve the problem
Usually we will declare this problem by throws on the function.
Purpose: In order for the caller to use this function, it is clear how to handle it. That is to say throws run out of the purpose is to
The
Let the caller pre-define how the problem is handled.
2, if a function throws multiple exceptions.
When you call this feature, you need to have multiple catch for each exception's targeted handling.
If there is a parent exception in multiple catch, be sure to define it at the bottom. Otherwise, the compilation fails.
3, Special parts:
Throw throws exception object inside function, must declare with throws on function. Otherwise, the compilation fails.
Call to the function declaring the exception, to declare the throws declaration thrown, or Trycatch capture, otherwise, the compilation fails.
Note: Exceptions are divided into two types.
1, the exception that is detected by the compiler at compile time.
It is often necessary to write the case-specific code for processing.
2, the exception that is not detected at compile time. This exception occurs when the compile time is not in the check list. This exception is called the runtime
Abnormal.
In other words, the throw throws a run-time exception and does not need to be declared on the function. Even if you declare the caller, you don't have to
Be sure to give a pre-treatment because she doesn't cause compilation to fail.
In order to make corrections to the code.
Differentiated by: A special subclass in exception: RuntimeException is a run-time exception.
Both Runtimeexception,exception and its subclasses do not require compile-time detection.
This means that we can inherit exception, known as the exception that was detected at compile time, when we were customizing the exception.
You can also inherit RuntimeException, called a run-time exception.

Class Demo
{
int div (int a,int b) throws ArithmeticException (Exception1,exception2,exception3)
{
return a/b;
int div (int a,int b) throws Exception
{
if (b==0)
{
throw new Exception ("exception");
}
int [] arr=new int[a];
if (b>=a)
throw new ArrayIndexOutOfBoundsException ("Corner label out of Bounds")
System.out.println (Arr[b])
}
}
Class Exception4
{
public static void Main (string[] args)
{
Demo D=new demo ();
int Num=d,div (4,1);
System.out.println ("num=" +num);
/*
try{
int X=d.div (4,0);
}
catch (Exception1 e)
{
}
catch (Exception2 e)
{
}
catch (Exception3 e)
{
}*/
}
}

}

He uses a computer to teach.
A malfunction occurred during the course of the class. such as computer blue screen, smoke.
Class Lanpingexception (String message)
{
Lanpingexception ()
{
Super ();
}
Maoyanexception (String)
}
Class computer

{
private int state=1;
public void Run ()
{
if (state==2)
throw new Lanpingexception ("Computer blue screen");
if (state==3)
throw new Maoyanexception ("Computer Smoke");
SYSTEM.OUT.PRINTLN ("Computer Run");

}
public void reset{
state=1;
SYSTEM.OUT.PRINTLN ("computer restart");
}
}
Class Teacher
{
private String name;
Private computer comp;
Teacher (String name)
{
This.name=name;
Comp=new computer ();
}
public void Prelect ()
{
try{
Comp.run ();

System.out.println (name+ "lectures");
}catch (lanpingexception e)
{
Restart your computer
Comp.reset ();
Prelect ();

}catch (maoyanexception e)
{
Test ();
Throw e;
throw new
}
}
public void Test ()
{
System.out.println ("everyone exercises");
}
Class Exception
{
public static void Main (string[] args)
{
Teacher t=new Teacher ("Teacher bi");
T.prelect ();
}
}

//

try{}
catch (Exception Class)
{
exception handling;
}
finally{
Code that is bound to be processed.
}
The return statement is written in the catch and finally will be executed.
void Add (data)
{
1 Connecting the database
2 Store data. An exception occurred when the storage failed.
3 Close the database connection. (Does not consume database resources)
}
Put connection and processing in try, catch (Database exception e)
{
Exception handling
}
finally{
The database must be closed.
Primarily used to release resources, some actions must be performed, regardless of whether an exception occurs.
}

System.exit (0);//exit the virtual machine, and finally will not execute.
In the case of exception snapping, different combinations of code blocks.
1,try Catch finally
2,try catch//There is no code that needs to be executed. This is usually an action that does not require a resource to be closed.
3,try finally. Handling exceptions only catch can be done. The exception is not processed, but it involves the resource's
Called, the resource needs to be closed, so the exception is declared because there is no catch, but the resource is
Can be opened internally, must be closed within the function, there is a combination of try and finally.


Exception the details in the overlay.
When a subclass overrides a parent class, if the overridden method throws an exception in the parent class, the method covered by the subclass can only throw a
The same exception, or subclass of the exception.

If the overriding method of the parent class throws more than one exception, the subclass can only throw a subset of those exceptions when overridden.
3, if the overridden method does not throw an exception, the subclass also does not allow the exception to be thrown, and if the subclass really appears to be an exception, only
Do try processing within a subclass method and never allow throws declarations. What if we can't handle it? You can choose to throw the run
The time exception.
Interface Inter
{
void Show ();

}
Class Interimpl implements Inter
{
public void Show ()
{
try{
throw new Exception ();
}
catch (Exception e)
{
throw new RuntimeException ("XXX exception information");
}
}
}

Java Base exception (Bi Xiangdong teacher)

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.