Въпроси за интервю за Java Exceptions (+ отговори)

Тази статия е част от поредица: • Въпроси за интервю за Java Collections

• Въпроси за интервю за система тип Java

• Въпроси за интервю за съвпадение на Java (+ отговори)

• Структура на Java клас и въпроси за интервю за инициализация

• Въпроси за интервю за Java 8 (+ отговори)

• Управление на паметта в Java Интервю въпроси (+ отговори)

• Въпроси за интервю за Java Generics (+ отговори)

• Въпроси за интервю за Java Flow Control (+ отговори)

• Въпроси за интервю за Java Exceptions (+ отговори) (текуща статия) • Въпроси за интервю за Java Annotations (+ отговори)

• Топ пролетни въпроси за интервю

1. Общ преглед

Изключенията са основна тема, с която всеки разработчик на Java трябва да е запознат. Тази статия предоставя отговори на някои от въпросите, които могат да се появят по време на интервю.

2. Въпроси

Q1. Какво е изключение?

Изключение е необичайно събитие, което се случва по време на изпълнението на програма и нарушава нормалния поток от инструкциите на програмата.

Q2. Каква е целта на Хвърляне и хвърляне на ключови думи?

В хвърлянията ключова дума се използва, за да се уточни, че метод може да предизвика изключение по време на неговото изпълнение. Той налага изрично обработване на изключения при извикване на метод:

public void simpleMethod() throws Exception { // ... }

На един хвърлей ключова дума ни дава възможност да се хвърли изключение обект, за да се прекъсне нормалното протичане на програмата. Това се използва най-често, когато дадена програма не успее да изпълни дадено условие:

if (task.isTooComplicated()) { throw new TooComplicatedException("The task is too complicated"); }

Q3. Как можете да се справите с изключение?

Чрез използване на инструкция try-catch-final :

try { // ... } catch (ExceptionType1 ex) { // ... } catch (ExceptionType2 ex) { // ... } finally { // ... }

Блокът с код, в който може да възникне изключение, е затворен в блок try . Този блок се нарича още „защитен“ или „защитен“ код.

Ако възникне изключение, блокът catch, който съответства на хвърленото изключение, се изпълнява, ако не, всички блокове catch се игнорират.

Най- накрая блок винаги се изпълнява, след като пробвам блокови изходите, независимо дали е направено изключение хвърлен или не вътре в нея.

Q4. Как можете да уловите множество изключения?

Има три начина за обработка на множество изключения в блок код.

Първият е да се използва блок за хващане, който може да обработва всички хвърляни видове изключения:

try { // ... } catch (Exception ex) { // ... }

Трябва да имате предвид, че препоръчителната практика е да се използват манипулатори на изключения, които са възможно най-точни.

Прекалено широките манипулатори на изключения могат да направят кода ви по-податлив на грешки, да улавят изключения, които не са били очаквани, и да причинят неочаквано поведение във вашата програма.

Вторият начин е реализиране на множество блокове за улов:

try { // ... } catch (FileNotFoundException ex) { // ... } catch (EOFException ex) { // ... }

Имайте предвид, че ако изключенията имат връзка по наследство; типът дете трябва да е на първо място, а типът родител по-късно. Ако не успеем да направим това, това ще доведе до грешка в компилацията.

Третото е да се използва блок с много улов:

try { // ... } catch (FileNotFoundException | EOFException ex) { // ... }

Тази функция, представена за първи път в Java 7; намалява дублирането на код и улеснява поддръжката.

Q5. Каква е разликата между проверено и непроверено изключение?

Провереното изключение трябва да се обработва в рамките на блока try-catch или да се декларира в клауза за хвърляне ; като има предвид, че не е необходимо да се обработва и декларира непроверено изключение.

Проверените и непроверени изключения са известни също като изключения по време на компилация и по време на изпълнение.

Всички изключения са отметнати изключения, с изключение на тези, посочени от Error , RuntimeException и техните подкласове.

Q6. Каква е разликата между изключение и грешка?

Изключение е събитие, което представлява състояние, от което е възможно възстановяване, докато грешката представлява външна ситуация, обикновено невъзможна за възстановяване.

Всички грешки, изхвърлени от JVM, са случаи на грешка или един от нейните подкласове, по-често срещаните включват, но не се ограничават до:

  • OutOfMemoryError - изхвърля се, когато JVM не може да разпредели повече обекти, защото няма памет, а събирачът на боклук не успя да направи повече достъпни
  • StackOverflowError - възниква, когато мястото на стека за една нишка изтече, обикновено защото приложението се повтаря твърде дълбоко
  • ExceptionInInitializerError - сигнализира, че е възникнало неочаквано изключение по време на оценката на статичен инициализатор
  • NoClassDefFoundError – is thrown when the classloader tries to load the definition of a class and couldn't find it, usually because the required class files were not found in the classpath
  • UnsupportedClassVersionError – occurs when the JVM attempts to read a class file and determines that the version in the file is not supported, normally because the file was generated with a newer version of Java

Although an error can be handled with a try statement, this is not a recommended practice since there is no guarantee that the program will be able to do anything reliably after the error was thrown.

Q7. What Exception Will Be Thrown Executing the Following Code Block?

Integer[][] ints = { { 1, 2, 3 }, { null }, { 7, 8, 9 } }; System.out.println("value = " + ints[1][1].intValue());

It throws an ArrayIndexOutOfBoundsException since we're trying to access a position greater than the length of the array.

Q8. What Is Exception Chaining?

Occurs when an exception is thrown in response to another exception. This allows us to discover the complete history of our raised problem:

try { task.readConfigFile(); } catch (FileNotFoundException ex) { throw new TaskException("Could not perform task", ex); }

Q9. What Is a Stacktrace and How Does It Relate to an Exception?

A stack trace provides the names of the classes and methods that were called, from the start of the application to the point an exception occurred.

It's a very useful debugging tool since it enables us to determine exactly where the exception was thrown in the application and the original causes that led to it.

Q10. Why Would You Want to Subclass an Exception?

If the exception type isn't represented by those that already exist in the Java platform, or if you need to provide more information to client code to treat it in a more precise manner, then you should create a custom exception.

Deciding whether a custom exception should be checked or unchecked depends entirely on the business case. However, as a rule of thumb; if the code using your exception can be expected to recover from it, then create a checked exception otherwise make it unchecked.

Also, you should inherit from the most specific Exception subclass that closely relates to the one you want to throw. If there is no such class, then choose Exception as the parent.

Q11. What Are Some Advantages of Exceptions?

Traditional error detection and handling techniques often lead to spaghetti code hard to maintain and difficult to read. However, exceptions enable us to separate the core logic of our application from the details of what to do when something unexpected happens.

Also, since the JVM searches backward through the call stack to find any methods interested in handling a particular exception; we gain the ability to propagate an error up in the call stack without writing additional code.

Also, because all exceptions thrown in a program are objects, they can be grouped or categorized based on its class hierarchy. This allows us to catch a group of exceptions in a single exception handler by specifying the exception's superclass in the catch block.

Q12. Can You Throw Any Exception Inside a Lambda Expression's Body?

When using a standard functional interface already provided by Java, you can only throw unchecked exceptions because standard functional interfaces do not have a “throws” clause in method signatures:

List integers = Arrays.asList(3, 9, 7, 0, 10, 20); integers.forEach(i -> { if (i == 0) { throw new IllegalArgumentException("Zero not allowed"); } System.out.println(Math.PI / i); });

However, if you are using a custom functional interface, throwing checked exceptions is possible:

@FunctionalInterface public static interface CheckedFunction { void apply(T t) throws Exception; }
public void processTasks( List taks, CheckedFunction checkedFunction) { for (Task task : taks) { try { checkedFunction.apply(task); } catch (Exception e) { // ... } } } processTasks(taskList, t -> { // ... throw new Exception("Something happened"); });

Q13. What Are the Rules We Need to Follow When Overriding a Method That Throws an Exception?

Several rules dictate how exceptions must be declared in the context of inheritance.

When the parent class method doesn't throw any exceptions, the child class method can't throw any checked exception, but it may throw any unchecked.

Here's an example code to demonstrate this:

class Parent { void doSomething() { // ... } } class Child extends Parent { void doSomething() throws IllegalArgumentException { // ... } }

The next example will fail to compile since the overriding method throws a checked exception not declared in the overridden method:

class Parent { void doSomething() { // ... } } class Child extends Parent { void doSomething() throws IOException { // Compilation error } }

When the parent class method throws one or more checked exceptions, the child class method can throw any unchecked exception; all, none or a subset of the declared checked exceptions, and even a greater number of these as long as they have the same scope or narrower.

Here's an example code that successfully follows the previous rule:

class Parent { void doSomething() throws IOException, ParseException { // ... } void doSomethingElse() throws IOException { // ... } } class Child extends Parent { void doSomething() throws IOException { // ... } void doSomethingElse() throws FileNotFoundException, EOFException { // ... } }

Note that both methods respect the rule. The first throws fewer exceptions than the overridden method, and the second, even though it throws more; they're narrower in scope.

However, if we try to throw a checked exception that the parent class method doesn't declare or we throw one with a broader scope; we'll get a compilation error:

class Parent { void doSomething() throws FileNotFoundException { // ... } } class Child extends Parent { void doSomething() throws IOException { // Compilation error } }

When the parent class method has a throws clause with an unchecked exception, the child class method can throw none or any number of unchecked exceptions, even though they are not related.

Here's an example that honors the rule:

class Parent { void doSomething() throws IllegalArgumentException { // ... } } class Child extends Parent { void doSomething() throws ArithmeticException, BufferOverflowException { // ... } }

Q14. Will the Following Code Compile?

void doSomething() { // ... throw new RuntimeException(new Exception("Chained Exception")); }

Yes. When chaining exceptions, the compiler only cares about the first one in the chain and, because it detects an unchecked exception, we don't need to add a throws clause.

Q15. Is There Any Way of Throwing a Checked Exception from a Method That Does Not Have a Throws Clause?

Yes. We can take advantage of the type erasure performed by the compiler and make it think we are throwing an unchecked exception, when, in fact; we're throwing a checked exception:

public  T sneakyThrow(Throwable ex) throws T { throw (T) ex; } public void methodWithoutThrows() { this.sneakyThrow(new Exception("Checked Exception")); }

3. Conclusion

В тази статия разгледахме някои от въпросите, които вероятно ще се появят в технически интервюта за разработчици на Java, по отношение на изключенията. Това не е изчерпателен списък и трябва да се третира само като начало на по-нататъшни изследвания.

Ние от Baeldung ви пожелаваме успех във всички предстоящи интервюта.

Напред » Въпроси за интервю за Java Annotations (+ отговори) « Предишни въпроси за интервю за Java Flow Control (+ отговори)