Basic java exception knowledge and some interview questions

Source: Internet
Author: User

Basic java exception knowledge and some interview questions

Java is an object-oriented design language, so exceptions are encapsulated into classes in java, and we only need to know how to handle exceptions,

Exception Overview

Exception: An exception occurs when the Java program is running.

Exception cause: the problem is also a specific transaction in real life. It can also be described in the form of java classes and encapsulated into objects. Actually, it is the embodiment of the object after Java describes the abnormal situation

Exception category


Program exception: Throwable
Serious problem: we will not handle the Error. This problem is generally very serious, such as memory overflow.
Problem: Exception
Compile-time problem: Not a RuntimeException exception must be handled, because compilation fails if you do not handle it.
Runtime problems: we will not deal with RuntimeException, because it is your problem, and this problem must be caused by the fact that our code is not rigorous enough to correct the code.

Example

The divisor is 0.

Public class ExceptionDemo {public static void main (String [] args) {// The first stage int a = 10; int B = 0; System. out. println (a/B); // The second stage System. out. println ("over ");}}
Running result:


We found that an exception was reported and the System. out. println ("over") was not output, that is, the jvm exited directly when it encountered an error,

Default JVM Solution

Output The Exception name, cause, location, and other information on the console, and the program stops running.

Exception Handling Scheme

1: try... Catch... Finally Exception Handling
2: throws an exception to the caller.

Let's talk about how to handle try... catch first.

Syntax format


Try {
Code that may cause problems;
} Catch (Exception name variable ){
Troubleshooting;
}
Note:
A: The less code the try, the better.
B: The catch must contain content, even a simple prompt.

Now try catch is used to process the above Code

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 ");}}
Running result:

Code error
Over

We found that the program encountered an error and the code was executed. Now, an exception occurs in the program. What if there are multiple exceptions? How to do

Solution

Write a try and multiple catch

Syntax format

Try {
Code that may be abnormal...
} Catch (exception class name variable name ){
Capture exceptions
}
Catch (exception class name variable name ){
Capture exceptions
}
In a catch statement, do not write the parent class exception at the beginning; otherwise, an error will occur in subsequent exception handling?

Correct syntax:

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 ("here is an exception. You don't know who it is. What should I do? ");} Catch (ArithmeticException e) {System. out. println ("Division cannot be 0");} catch (ArrayIndexOutOfBoundsException e) {System. out. println ("You have accessed the index you shouldn't have accessed");} catch (Exception e) {System. out. println ("something went wrong");} System. out. println ("over ");}}
If catch (Exception e) {System. out. println ("something went wrong");} This writing method is incorrect at the very beginning. Because Exception is a top-level parent class, it means it can handle any exceptions, so the subsequent subclass exceptions are not needed,

Incorrect syntax



Summary:

1: Be clear as much as possible and do not use big ones for handling.
2: It doesn't matter who is the exception of a level-level relationship. If a child-parent relationship exists, the parent must be later.


Once a problem occurs in try, the problem will be thrown here and matched with the problem in catch,
Once a match exists, execute the processing in the catch and end the try... catch process.
Continue executing the following statement


Differences between compile-time exceptions and runtime exceptions

Exceptions in Java are classified into two categories: compile-time exceptions and runtime exceptions. All RuntimeException classes and their subclass instances are called runtime exceptions. Other exceptions are compilation exceptions.
Exception during compilation
The Java program must be displayed for processing; otherwise, an error occurs in the program and compilation fails.
Runtime exception
No display processing is required, and the exception can be handled in the same way as during compilation.


Now let's talk about the common methods in Throwable.

GetMessage ()
Obtains the exception information and returns a string.
ToString ()
Obtains the exception class name and exception information, and returns a string.
PrintStackTrace ()
Obtain the exception class name and exception information, and the location where the exception occurs in the program. Return Value void.
PrintStackTrace (PrintStream s)
This method is usually used to save the exception content in the log file for reference.


At the beginning, I started to talk about the two methods of exception handling, but I talked about one method, and the other method that I didn't talk about. Now I will talk about another method of exception handling.

Throws Throw means that it is not processed here. It is thrown directly. Who calls and who handles the throws?

Throws Function Description

When defining functional methods, you need to expose the problems and let the caller handle them. Then it is identified by throws on the method.

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 syntax for throws to throw exceptions.

Syntax format

Throws exception class name

Note: The format must be followed by the brackets of the method.


There is also a way to solve the exception, but it is rarely used, that is, throw. The following is a brief overview of throw.

In some internal situations of function methods, the program cannot continue to run. When a jump is required, throw the exception object

Code

public class ExceptionDemo {public static void main(String[] args) {try {method2();} catch (Exception e) {e.printStackTrace();}}public static void method2() throws Exception {int a = 10;int b = 0;if (b == 0) {throw new ArithmeticException();} else {System.out.println(a / b);}}}

Now let's talk about common questions about exceptions.

1: difference between throws and throw

Throws
Used after the method declaration, with the exception class name
Can be separated with multiple exception class names by commas
Indicates that an exception is thrown and is handled by the caller of this method.
Throws indicates a possibility of exceptions. These exceptions may not occur.
Throw
Used in the method body with the exception Object Name
Only one exception object name can be thrown
Throws an exception and is processed by the statement in the method body.
Throw throws an exception, and throw an exception.


Another important point is the finally statement,

Features of finally statements

The statement body controlled by finally must be executed.
Special case: the jvm exits before it is executed to finally (for example, System. exit (0 ))

Role of finally

This API is used to release resources and will be seen in IO stream operations and database operations.

Finally statements are used together with try. The following methods are commonly used in combination:

Try... Catch... Finally available
Try... Catch can also be used
Try... Finally can also be used
However, catch and finally cannot be used separately.


Finally-related Interview Questions

Differences between final, finally and finalize
Final: The final meaning. It can be used to modify classes, member variables, and member methods.
Modifier Class, Class cannot be inherited
Modifies a variable. The variable is a constant.
Modification method. The method cannot be overwritten.
Finally: A part of exception handling, used to release resources.
Generally, the code will be executed. In special cases, the jvm exits before it is executed to finally.
Finalize: A method of the Object class for garbage collection.


If there is a return statement in catch, will finally code be executed? If yes, will it be before or after return?

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 = 20;} catch (ArithmeticException e) {a = 30; return a;/** return a when the program executes this step, return 30 is not a return a, but a return path. * However, it finds that there is still finally behind it, So continue to execute finally content, a = 40 * return to the previous return path again and continue to return 30; */} finally {a = 40;} return ;}}
This returns 30

Reason: As mentioned above, what if there is a return statement in the finally statement? What will be returned?

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 = 20;} catch (ArithmeticException e) {a = 30; return a;} finally {a = 40; return; // In this case, the result is 40 .}}}

The returned result is 40 because the return path already exists in the finally statement, so the answer is 40.

Now the last technical point is the custom exception.

Custom exception

Java cannot take all the situations into consideration. Therefore, in actual development, we may need to define exceptions by ourselves.
However, if we write a class at will, it cannot be regarded as an Exception class. If we want your class to be an Exception class, we must inherit from Exception or RuntimeException.


Two methods:
A: inherits Exception
B: Inherit RuntimeException

Write an example to understand the requirement. The test score must be between 0 and.

MyException. java custom exception class

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


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

Teacher. java service class

Public class Teacher {
Public void check (int score) throws MyException {
If (score> 100 | score <0 ){
Throw new MyException ("the score must be between 0 and ");
} Else {
System. out. println ("No score problem ");
}
}
}
StudentDemo. java test class

Public class StudentDemo {
Public static void main (String [] args ){
Pipeline SC = new pipeline (System. in );
System. out. println ("Enter the 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 precautions

When a subclass overrides the parent class method, the subclass method must throw the same exception or a subclass of the parent class exception.
If the parent class throws multiple exceptions, the Child class can only throw the same exception or its subset when rewriting the parent class. The Child class cannot throw exceptions that the parent class does not have.
If no exception is thrown for the method to be overwritten, The subclass method cannot throw an exception. If an exception occurs in the subclass method, the subclass can only try, not throws

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.