国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java JavaInterview questions 2020 New Java Interview Questions-Exception

2020 New Java Interview Questions-Exception

Jun 17, 2020 pm 05:12 PM
java abnormal Interview questions

2020 New Java Interview Questions-Exception

1. What is the difference between throw and throws?

throws is used to declare all exception information that a method may throw. throws is to declare the exception but not handle it. Instead, it will upload the exception and let whoever calls me handle it. Throw refers to a specific exception type thrown.

2. What is the difference between final, finally and finalize?

final can modify classes, variables, and methods. Modified class means that the class cannot be inherited, modified method means that the method cannot be overridden, and modified variable means that the variable is a constant and cannot be reassigned.

finally is generally used in try-catch code blocks. When handling exceptions, we usually put the code method that must be executed in the finally code block, which means that the code block will be executed regardless of whether an exception occurs. Generally Used to store some code for closing resources.

(Video tutorial recommendation: java video tutorial)

finalize is a method, belonging to the Object class, and the Object class is the parent class of all classes. The method is generally called by the garbage collector. When we call the System's gc() method, the garbage collector calls finalize() to collect garbage.

3. Which part of try-catch-finally can be omitted?

Answer: catch can be omitted

Reason:

A more strict statement is: try is only suitable for handling runtime exceptions, try catch is suitable for handling runtime exceptions Exception Ordinary Exception. In other words, if you only use try to handle ordinary exceptions without using catch, the compilation will not pass, because the compiler rigidly stipulates that if you choose to catch ordinary exceptions, you must use catch to explicitly declare them for further processing. There is no such provision for runtime exceptions at compile time, so catch can be omitted, and there is nothing wrong with adding the catch compiler.

Theoretically, the compiler is displeased with any code and thinks there may be potential problems, so even if you add try to all the code, the code will only run normally during runtime. Add a layer of skin. But once you add try to a piece of code, you are explicitly promising the compiler to catch the exceptions that may be thrown by this piece of code instead of throwing them upward. If it is a normal exception, the compiler requires that it must be caught with catch for further processing; if it is a runtime exception, it is caught and then discarded and finally cleaned up, or a catch is added for further processing.

As for adding finally, it is a "clean-up" process that must be performed regardless of whether an exception is caught or not.

(recommended related tutorials: java introductory program)

4. In try-catch-finally, if return is made in catch, will finally still be executed? ?

Answer: It will be executed before return.

Code example 1:

 
/*
 * java面試題--如果catch里面有return語句,finally里面的代碼還會執(zhí)行嗎?
 */
public class FinallyDemo2 {
    public static void main(String[] args) {
        System.out.println(getInt());
    }
 
    public static int getInt() {
        int a = 10;
        try {
            System.out.println(a / 0);
            a = 20;
        } catch (ArithmeticException e) {
            a = 30;
            return a;
            /*
             * return a 在程序執(zhí)行到這一步的時候,這里不是return a 而是 return 30;這個返回路徑就形成了
             * 但是呢,它發(fā)現(xiàn)后面還有finally,所以繼續(xù)執(zhí)行finally的內(nèi)容,a=40
             * 再次回到以前的路徑,繼續(xù)走return 30,形成返回路徑之后,這里的a就不是a變量了,而是常量30
             */
        } finally {
            a = 40;
        }
 
//      return a;
    }
}

Execution result: 30

Code example 2:

 
package com.java_02;
 
/*
 * java面試題--如果catch里面有return語句,finally里面的代碼還會執(zhí)行嗎?
 */
public class FinallyDemo2 {
    public static void main(String[] args) {
        System.out.println(getInt());
    }
 
    public static int getInt() {
        int a = 10;
        try {
            System.out.println(a / 0);
            a = 20;
        } catch (ArithmeticException e) {
            a = 30;
            return a;
            /*
             * return a 在程序執(zhí)行到這一步的時候,這里不是return a 而是 return 30;這個返回路徑就形成了
             * 但是呢,它發(fā)現(xiàn)后面還有finally,所以繼續(xù)執(zhí)行finally的內(nèi)容,a=40
             * 再次回到以前的路徑,繼續(xù)走return 30,形成返回路徑之后,這里的a就不是a變量了,而是常量30
             */
        } finally {
            a = 40;
            return a; //如果這樣,就又重新形成了一條返回路徑,由于只能通過1個return返回,所以這里直接返回40
        }
 
//      return a;
    }
}

Execution result: 40

5. What are the common exception types?

  • NullPointerException: This exception is thrown when the application attempts to access a null object.

  • SQLException: Exception that provides information about database access errors or other errors.

  • IndexOutOfBoundsException: Thrown when indicating that a sorting index (such as sorting an array, string, or vector) is out of range.

  • NumberFormatException: This exception is thrown when the application attempts to convert a string to a numeric type, but the string cannot be converted to the appropriate format.

  • FileNotFoundException: This exception is thrown when an attempt to open the file represented by the specified pathname fails.

  • IOException: This exception is thrown when some kind of I/O exception occurs. This class is a general class for exceptions generated by failed or interrupted I/O operations.

  • ClassCastException: This exception is thrown when an attempt is made to cast an object to a subclass that is not an instance.

  • ArrayStoreException: Exception thrown when trying to store an object of the wrong type into an object array.

  • IllegalArgumentException: An exception thrown indicating that an illegal or incorrect parameter was passed to the method.

  • ArithmeticException: This exception is thrown when an abnormal operation condition occurs. For example, when an integer is "divided by zero", an instance of this class is thrown.

  • NegativeArraySizeException: This exception is thrown if the application attempts to create an array with a negative size.

  • NoSuchMethodException: This exception is thrown when a specific method cannot be found.

  • SecurityException: Exception thrown by the security manager to indicate a security violation.

  • UnsupportedOperationException: This exception is thrown when the requested operation is not supported.

  • RuntimeExceptionRuntimeException: is the super class of exceptions that may be thrown during the normal operation of the Java virtual machine.

If you want to know more about interview questions, please visit java interview questions.

The above is the detailed content of 2020 New Java Interview Questions-Exception. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Using HTML `input` Types for User Data Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

go by example http middleware logging example go by example http middleware logging example Aug 03, 2025 am 11:35 AM

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

See all articles