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里面的代码还会执行吗?
 */
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 在程序执行到这一步的时候,这里不是return a 而是 return 30;这个返回路径就形成了
             * 但是呢,它发现后面还有finally,所以继续执行finally的内容,a=40
             * 再次回到以前的路径,继续走return 30,形成返回路径之后,这里的a就不是a变量了,而是常量30
             */
        } finally {
            a = 40;
        }
 
//      return a;
    }
}
Copy after login

Execution result: 30

Code example 2:

 
package com.java_02;
 
/*
 * java面试题--如果catch里面有return语句,finally里面的代码还会执行吗?
 */
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 在程序执行到这一步的时候,这里不是return a 而是 return 30;这个返回路径就形成了
             * 但是呢,它发现后面还有finally,所以继续执行finally的内容,a=40
             * 再次回到以前的路径,继续走return 30,形成返回路径之后,这里的a就不是a变量了,而是常量30
             */
        } finally {
            a = 40;
            return a; //如果这样,就又重新形成了一条返回路径,由于只能通过1个return返回,所以这里直接返回40
        }
 
//      return a;
    }
}
Copy after login

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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles