Soalan Temuduga Pengecualian Java (+ Jawapan)

Artikel ini adalah sebahagian daripada siri: • Pertanyaan Temuduga Koleksi Java

• Soalan Temuduga Sistem Jenis Java

• Pertanyaan Temuduga Bersama Java (+ Jawapan)

• Soalan Temuduga Struktur dan Permulaan Kelas Java

• Soalan Temuduga Java 8 (+ Jawapan)

• Pengurusan Memori dalam Soalan Temuduga Java (+ Jawapan)

• Soalan Temuduga Generik Java (+ Jawapan)

• Soalan Temuduga Kawalan Aliran Java (+ Jawapan)

• Soalan Temuduga Pengecualian Java (+ Jawapan) (artikel semasa) • Soalan Temuduga Anotasi Java (+ Jawapan)

• Soalan Temuduga Kerangka Musim Bunga Teratas

1. Gambaran keseluruhan

Pengecualian adalah topik penting yang harus diketahui oleh setiap pembangun Java. Artikel ini memberikan jawapan kepada beberapa pertanyaan yang mungkin muncul semasa wawancara.

2. Soalan

S1. Apakah Pengecualian?

Pengecualian adalah kejadian tidak normal yang berlaku semasa pelaksanaan program dan mengganggu aliran normal arahan program.

S2. Apakah Tujuan Kata Kunci Lemparan dan Lemparan?

Kata kunci lontaran digunakan untuk menentukan bahawa kaedah dapat menimbulkan pengecualian selama pelaksanaannya. Ini menerapkan pengendalian pengecualian eksplisit ketika memanggil kaedah:

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

Kata kunci lontaran membolehkan kita membuang objek pengecualian untuk mengganggu aliran normal program. Ini paling sering digunakan apabila program gagal memenuhi syarat tertentu:

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

S3. Bagaimana Anda Boleh Menangani Pengecualian?

Dengan menggunakan pernyataan try-catch-akhirnya :

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

Blok kod di mana pengecualian mungkin berlaku disertakan dalam blok percubaan . Blok ini juga disebut "dilindungi" atau "dijaga" kod.

Sekiranya pengecualian berlaku, blok tangkapan yang sesuai dengan pengecualian yang dilemparkan dilaksanakan, jika tidak, semua blok tangkapan diabaikan.

Yang akhirnya blok pasti berlaku selepas cuba keluar blok, sama ada pengecualian telah dibuang atau tidak di dalamnya.

S4. Bagaimana Anda Boleh Menangkap Pelbagai Pengecualian?

Terdapat tiga cara menangani beberapa pengecualian dalam sekatan kod.

Yang pertama adalah menggunakan blok penangkap yang dapat menangani semua jenis pengecualian yang dilemparkan:

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

Anda harus ingat bahawa amalan yang disarankan adalah menggunakan pengendali pengecualian yang seakurat mungkin.

Pengendali pengecualian yang terlalu luas dapat membuat kod anda lebih mudah ralat, menangkap pengecualian yang tidak dijangkakan, dan menyebabkan tingkah laku yang tidak dijangka dalam program anda.

Cara kedua adalah melaksanakan beberapa blok tangkapan:

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

Perhatikan bahawa, jika pengecualian mempunyai hubungan warisan; jenis anak mesti didahulukan dan jenis ibu bapa kemudian. Sekiranya kita gagal melakukan ini, ia akan menyebabkan kesalahan penyusunan.

Yang ketiga adalah menggunakan blok multi-tangkapan:

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

Ciri ini, pertama kali diperkenalkan di Java 7; mengurangkan pertindihan kod dan menjadikannya lebih mudah untuk dijaga.

S5. Apakah Perbezaan Antara Pengecualian yang Diperiksa dan yang Tidak Diperiksa?

Pengecualian yang diperiksa mesti dikendalikan dalam blok cubaan atau dinyatakan dalam klausa lemparan ; sedangkan pengecualian yang tidak diperiksa tidak perlu ditangani atau dinyatakan.

Pengecualian yang dicentang dan tidak dicentang juga masing-masing dikenali sebagai pengecualian waktu kompilasi dan masa berjalan.

Semua pengecualian adalah pengecualian yang diperiksa, kecuali yang ditunjukkan oleh Ralat , RuntimeException , dan subkelasnya.

S6. Apakah Perbezaan Antara Pengecualian dan Kesalahan?

Pengecualian adalah peristiwa yang mewakili keadaan yang mungkin dapat dipulihkan, sedangkan kesalahan menunjukkan keadaan luaran yang biasanya tidak dapat dipulihkan.

Semua kesalahan yang dilemparkan oleh JVM adalah contoh Kesalahan atau salah satu subkelasnya, yang lebih biasa termasuk tetapi tidak terhad kepada:

  • OutOfMemoryError - dilemparkan apabila JVM tidak dapat memperuntukkan lebih banyak objek kerana memori sudah habis, dan pengumpul sampah tidak dapat menyediakan lebih banyak
  • StackOverflowError - berlaku apabila ruang tumpukan untuk utas habis, biasanya kerana aplikasi berulang terlalu dalam
  • ExceptionInInitializerError - memberi isyarat bahawa pengecualian yang tidak dijangka berlaku semasa penilaian pemula yang statik
  • 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

Dalam artikel ini, kami telah menjelajahi beberapa pertanyaan yang mungkin muncul dalam wawancara teknikal untuk pembangun Java, mengenai pengecualian. Ini bukan senarai yang lengkap, dan hanya boleh dianggap sebagai permulaan penyelidikan lebih lanjut.

Kami, di Baeldung, mengucapkan kejayaan dalam temu ramah yang akan datang.

Seterusnya » Soalan Temuduga Anotasi Java (+ Jawapan) « Soalan Temuduga Kawalan Aliran Java Sebelumnya (+ Jawapan)