Java exception basics and some face questions

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

Java is an object-oriented design language, so exceptions are encapsulated in Java, and we just have to know how to handle exceptions.

Exceptions overview

Exception: An exception is an error that occurs while the Java program is running.

Exception Origin: The problem is also a real life of a specific transaction, can also be described in the form of Java classes, and encapsulated into objects. In fact, Java is the object of the description of the abnormal situation after the embodiment

Exception classification


Exception to program: Throwable
Serious problem: Error we do not handle. This kind of problem is usually very serious, for example memory overflow.
Question: Exception
Compile time problem: The exception that is not runtimeexception must be handled, because you do not process, the compilation cannot pass.
Run-time issue: RuntimeException This problem we also do not deal with, because it is your problem, and this problem appears certainly is our code is not rigorous, need to fix the code .

Example

Divisor is 0

public class Exceptiondemo {public static void main (string[] args) {//first stage int a = 10;int b = 0; System.out.println (A/b);//Second Stage System.out.println ("Over");}}
Operation Result:


We found the exception error, and the following sentence System.out.println ("over"), no output, that is, the JVM has encountered an error to exit directly,

Default processing scheme for JVM

The name of the exception, the cause of the error and the location of the exception appear in the console, the program stops execution

Exception Handling Scenarios

1:try...catch...finally Handling Exceptions
2:throws throws an exception to the caller

Let's start with the try...catch approach.

Syntax format


try {
Code that may be problematic;
}catch (Exception name variable) {
deal with the problem;
}
Attention:
The less code inside the A:try, the better.
B:catch inside must have content, even give a simple hint

The above code is now processed using the try Catch

public class Exceptiondemo {public static void main (string[] args) {int a = 10;int B = 0;try{system.out.println (A/b);} catch (Exception e) {System.out.println ("code Error");} System.out.println ("Over");}}
Operation Result:

The code went wrong.
Over

We found that the program error was captured by us, and the following code is also executed, and now the program has an exception, if there are multiple exceptions?

Solution Solutions

Write a try, multiple catch

Syntax format

try{
Code that may appear to be abnormal ...
}catch (Exception class name variable name) {
Catching exceptions
}
catch (Exception class name variable name) {
Catching exceptions
}
Do not write the parent exception in the catch statement at the top, otherwise the exception handling will go wrong?

The correct wording:

public class ExceptionDemo2 {public static void main (string[] args) {method4 ();} public static void Method4 () {int a = 10;int B = 0;int[] arr = {1, 2, 3};try {System.out.println (A/b); System.out.println (Arr[3]); System.out.println ("There's an anomaly here, you don't know who it is, what to do?"); catch (ArithmeticException e) {System.out.println ("divisor cannot be 0");} catch (ArrayIndexOutOfBoundsException e) { System.out.println ("You visited the index of the wrong Access");} catch (Exception e) {System.out.println ("problem");} System.out.println ("Over");}}
If you put catch (Exception e) {System.out.println ("problem");} It is wrong to write in the first, because exception is a top-level parent class that represents the ability to handle any exception, so the following subclass exception is not required.

Wrong wording



Summarize:

1: Can clear as far as possible clear, do not use the big to deal with.
2: The exception of the relationship between the peer who before who does not matter, if a child parent relationship, the parent must be in the back.


Once something goes wrong in the try, it throws the problem here and matches the problem in the catch.
Once there is a match, execute the handle inside the catch and then end the Try...catch
Continue execution of the following statement


Differences between compile-time exceptions and run-time exceptions

Exceptions in Java are divided into two main classes: compile-time exceptions and run-time exceptions. All instances of the RuntimeException class and its subclasses are called run-time exceptions, and other exceptions are compile-time exceptions
Compile-time exceptions
The Java program must show processing, or the program will have an error and cannot be compiled
Run-time exception
No need to display processing, or to be treated as a compile-time exception


Now let's talk about the methods commonly used in Throwable.

GetMessage ()
Gets the exception information that returns the string.
ToString ()
Gets the exception class name and exception information, which returns a string.
Printstacktrace ()
Gets the exception class name and exception information, and the location where the exception appears in the program. return value void.
Printstacktrace (PrintStream s)
You typically use this method to save the exception content in a log file for review.


Just started to say the exception handling of the 2 way, but the one, there is a way to deal with, and now tell the exception of another way to deal with

Throws throws the meaning, that is, not to handle this, directly throws, who calls who handles

Throws function description

When defining a functional method, it is necessary to expose the problem to the caller for processing. Then the method is identified by throws.

Code

public class Exceptiondemo{public static void Main (string[] args) throws Exception  {int a = 10;int b = 0; System.out.println (A/b); System.out.println ("Over");}}

Now let's talk about the correct wording of the throws throw exception

Syntax format

Throws Exception class name

Note: This format must be followed by the parentheses of the method


There is also a way to solve the exception, but rarely used, that is, throw, the following is a brief summary of the throw

There is a situation inside the function method, the program can not continue to run, need to jump, throw the exception object with throw

Code

public class Exceptiondemo {public static void main (string[] args) {try {method2 ()} catch (Exception e) {E.printstacktrac E ();}} public static void Method2 () throws Exception {int a = 10;int B = 0;if (b = = 0) {throw new ArithmeticException ();} else {S Ystem.out.println (A/b);}}}

Now, let's talk about the common questions about anomalies.

The difference between 1:throws and throw

Throws
Used after the method declaration, followed by the exception class name
Can be separated by a comma with multiple exception class names
Represents a thrown exception that is handled by the caller of the method
Throws represents a possibility of an exception that does not necessarily occur
Throw
Used in the body of a method, followed by the name of the exception object
Only one exception object name can be thrown
Represents a thrown exception, handled by a statement in the method body
Throw throws an exception, and execution throws must throw some kind of exception.


We also have an important point of knowledge not to say, is the finally statement,

Features of the Finally statement

The statement body that is finally controlled is bound to execute
Special case: The JVM exits before execution to finally (e.g. System.exit (0))

The role of finally

Used to free up resources, and in IO stream operations and database operations, you will see

The finally statement is used together with the collection try, and the commonly used collocation methods are as follows

Try...catch...finally can be used
Try...catch can also be used
Try...finally can also be used
However, catch,finally cannot be used alone


Finally-related face questions

The difference between final,finally and finalize
Final: Ultimate Meaning, can be modified class, member variable, member method
Modifier class, class cannot be inherited
Modifier variable, variable is constant
Modification method, method cannot be overridden
Finally: is part of exception handling for freeing resources.
In general, the code will definitely execute, special cases: the JVM exits before executing to finally
Finalize: Is a method of the object class for garbage collection


If there is a return statement inside the catch, will the finally code be executed? If so, is it before or after return?

<span style= "FONT-SIZE:18PX;" >public class Exceptiondemo{public static void Main (string[] args) throws Exception  {System.out.println (GetInt ( ));} @SuppressWarnings ("finally") public static int getInt () {int a = 10;try {System.out.println (a/0); a =;} catch (Arithmet Icexception e) {a = 30;return a;/* * Return a when the program executes to this step, this is not return a but return 30; The return path is formed. * But, it found that there is finally, so continue to execute finally content, a=40 * Again back to the previous return path, continue to walk return 30; */} finally {a = 40;} return A;}} </span>
This is a return of

Reason: It has been commented that if there is a return statement in the finally statement, how much will it return?

<span style= "FONT-SIZE:18PX;" >public class Exceptiondemo{public static void Main (string[] args) throws Exception  {System.out.println (GetInt ( ));} @SuppressWarnings ("finally") public static int getInt () {int a = 10;try {System.out.println (a/0); a =;} catch (Arithmet Icexception e) {a = 30;return A;} finally {a = 40;return a;//If the result is 40. }}}</span>

This return is 40 because the return path is already in the finally statement, so the answer is

Now, the last technical point is to customize the exception.

Custom exceptions

Java is not likely to be considered in all cases, so in actual development we may need to define the exception ourselves.
And our own arbitrary write a class, is not as the exception class to see, to think your class is an exception class, you must inherit from exception or RuntimeException


Two different ways:
A: Inheriting exception
B: Inherit RuntimeException

Write an example to understand: demand; test scores must be between 0-100

Myexception.java Custom Exception Classes

public class MyException extends Exception {
Public MyException () {
}


Public myexception (String message) {
Super (message);
}
}

Teacher.java Business Class

public class Teacher {
public void check ( int score) throws MyException {
if (Score > | | Score < 0) {
throw new MyException ("score must be between 0-100");
} else {
System.out.println (" Score no Problem ");
}
}
}
Studentdemo.java Business test class

public class Studentdemo {
public static void Main (string[] args) {
Scanner sc = new Scanner (system.in);
System.out.println ("Please enter student score:");
int score = Sc.nextint ();


Teacher t = new Teacher ();
try {
T.check (score);
} catch (MyException e) {
E.printstacktrace ();
}
}
}

OK custom exception is so simple!

Exception considerations

When a subclass overrides a parent class method, the child class's method must throw the same exception or subclass of the parent class exception
If the parent class throws more than one exception, when the subclass overrides the parent class, it can only throw the same exception or a subset of his, the subclass cannot throw exceptions that the parent class does not have
If the overridden method does not throw an exception, then the method of the subclass is absolutely not allowed to throw an exception, and if an exception occurs within the subclass method, then the subclass can only try, not throws

Java exception basics and some face questions

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.