Pertanyaan Wawancara Pengecualian Java (+ Jawaban)

Artikel ini adalah bagian dari serial: • Pertanyaan Wawancara Koleksi Java

• Pertanyaan Wawancara Sistem Jenis Java

• Pertanyaan Wawancara Konkurensi Java (+ Jawaban)

• Struktur Kelas Java dan Pertanyaan Wawancara Inisialisasi

• Java 8 Pertanyaan Wawancara (+ Jawaban)

• Manajemen Memori dalam Pertanyaan Wawancara Java (+ Jawaban)

• Pertanyaan Wawancara Umum Java (+ Jawaban)

• Pertanyaan Wawancara Kontrol Aliran Java (+ Jawaban)

• Pertanyaan Wawancara Pengecualian Jawa (+ Jawaban) (artikel saat ini) • Pertanyaan Wawancara Anotasi Jawa (+ Jawaban)

• Pertanyaan Wawancara Top Spring Framework

1. Ikhtisar

Pengecualian adalah topik penting yang harus dipahami oleh setiap pengembang Java. Artikel ini memberikan jawaban atas beberapa pertanyaan yang mungkin muncul selama wawancara.

2. Pertanyaan

P1. Apa Itu Pengecualian?

Pengecualian adalah kejadian abnormal yang terjadi selama pelaksanaan program dan mengganggu aliran normal instruksi program.

P2. Apa Tujuan dari Kata Kunci Lempar dan Lempar?

Kata kunci throws digunakan untuk menentukan bahwa suatu metode dapat memunculkan pengecualian selama eksekusinya. Ini memberlakukan penanganan pengecualian eksplisit saat memanggil metode:

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

Kata kunci throw memungkinkan kita untuk melempar objek pengecualian untuk mengganggu aliran normal program. Ini paling sering digunakan ketika program gagal memenuhi kondisi tertentu:

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

P3. Bagaimana Anda Dapat Menangani Pengecualian?

Dengan menggunakan pernyataan coba-tangkap-akhirnya :

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

Blok kode di mana pengecualian dapat terjadi diapit dalam blok percobaan . Blok ini juga disebut kode "dilindungi" atau "dilindungi".

Jika pengecualian terjadi, blok catch yang cocok dengan pengecualian yang dilempar akan dieksekusi, jika tidak, semua blok catch akan diabaikan.

The akhirnya blok selalu dilaksanakan setelah mencoba keluar blok, apakah pengecualian terlempar atau tidak di dalamnya.

P4. Bagaimana Cara Menangkap Beberapa Pengecualian?

Ada tiga cara menangani beberapa pengecualian dalam satu blok kode.

Yang pertama adalah menggunakan blok catch yang dapat menangani semua tipe pengecualian yang dilemparkan:

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

Anda harus ingat bahwa praktik yang disarankan adalah menggunakan penangan pengecualian yang seakurat mungkin.

Penangan pengecualian yang terlalu luas dapat membuat kode Anda lebih rentan terhadap kesalahan, menangkap pengecualian yang tidak diantisipasi, dan menyebabkan perilaku yang tidak terduga dalam program Anda.

Cara kedua adalah menerapkan beberapa blok tangkapan:

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

Perhatikan bahwa, jika pengecualian memiliki hubungan warisan; tipe anak harus didahulukan dan tipe induk nanti. Jika kami gagal melakukan ini, itu akan menghasilkan kesalahan kompilasi.

Yang ketiga adalah menggunakan blok multi-tangkapan:

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

Fitur ini, pertama kali diperkenalkan di Java 7; mengurangi duplikasi kode dan membuatnya lebih mudah dikelola.

P5. Apa Perbedaan Antara Pengecualian yang Dicentang dan yang Tidak Dicentang?

Pengecualian yang dicentang harus ditangani dalam blok coba-tangkap atau dideklarasikan dalam klausa lemparan ; sedangkan pengecualian yang tidak dicentang tidak perlu ditangani atau dideklarasikan.

Pengecualian yang dicentang dan yang tidak juga dikenal sebagai pengecualian waktu kompilasi dan waktu proses.

Semua pengecualian diperiksa pengecualian, kecuali yang ditunjukkan oleh Error , RuntimeException , dan subclassnya.

P6. Apa Perbedaan Antara Pengecualian dan Kesalahan?

Pengecualian adalah peristiwa yang mewakili kondisi yang memungkinkan untuk dipulihkan, sedangkan kesalahan mewakili situasi eksternal yang biasanya tidak mungkin untuk dipulihkan.

Semua kesalahan yang dilemparkan oleh JVM adalah contoh Kesalahan atau salah satu subkelasnya, yang lebih umum termasuk tetapi tidak terbatas pada:

  • OutOfMemoryError - muncul ketika JVM tidak dapat mengalokasikan lebih banyak objek karena kehabisan memori, dan pengumpul sampah tidak dapat menyediakan lebih banyak
  • StackOverflowError - terjadi ketika ruang tumpukan untuk utas telah habis, biasanya karena aplikasi berulang terlalu dalam
  • ExceptionInInitializerError - menandakan bahwa pengecualian tak terduga terjadi selama evaluasi penginisialisasi statis
  • 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

Pada artikel ini, kami telah menjelajahi beberapa pertanyaan yang mungkin muncul dalam wawancara teknis untuk pengembang Java, terkait pengecualian. Ini bukanlah daftar yang lengkap, dan ini harus diperlakukan hanya sebagai awal dari penelitian lebih lanjut.

Kami, di Baeldung, berharap Anda sukses dalam wawancara yang akan datang.

Berikutnya » Pertanyaan Wawancara Anotasi Java (+ Jawaban) « Sebelumnya Pertanyaan Wawancara Kontrol Aliran Java (+ Jawaban)