Java Exceptions Interview Questions And Answers

22 Java Exceptions Interview Questions And Answers – Exceptions in Java Interview Questions For Experienced from Codingcompiler. Test your Java Exceptions knowledge by answering these tricky interview questions on Java exceptions. Let’s start learning Java exceptions interview questions and prepare for Java interviews. All the best for your future and happy learning.

Table of Contents

Java Exceptions Interview Questions

  1. Define the concept of “exception”
  2. What is the hierarchy of exceptions.
  3. Is it possible to process jvm errors?
  4. What are the ways to handle exceptions?
  5. What does the throws keyword mean?
  6. What are the features of the finally block? Is it always performed?
  7. Can there be a single catch block when catching exceptions?
  8. Could you think of a situation where the finally block will not be executed?
  9. Can a single catch block catch several exceptions (from the same and different branches of inheritance)?
  10. What do you know about catched / uncatched exceptions?
  11. What are the features of RuntimeException?
  12. How to write own (“user”) exception? What motives will you follow when choosing the type of an exception: checked / unchecked?
  13. Which operator allows you to forcibly throw an exception?
  14. Are there additional conditions to the method that could potentially throw an exception?
  15. Can the main method throw an exception to the outside, and if so, where will the exception be processed?
  16. If the return statement is contained in both the catch block and finally, which one is “superior”?
  17. What do you know about OutOfMemoryError?
  18. What do you know about SQLException? What type of checked or unchecked is it, why?
  19. What is Error? In which case Error is used. Give an example of Error.
  20. What construction is used in Java for exception handling?
  21. Suppose there is a try-finally block. An exception was thrown in the try block and the execution moved to the finally block. An exception also occurred in the finally block. Which of the two exceptions will be dropped from the try-finally block? What happens to the second exception?
  22. Suppose there is a method that can throw an IOException and a FileNotFoundException in which sequence should the catch blocks go? How many catch blocks will be executed?

Related Java Interview Questions

  1. Java OOPS Interview Questions
  2. Core Java Interview Questions
  3. JSF Interview Questions
  4. JSP Interview Questions
  5. JPA Interview Questions
  6. Spring Framework Interview Questions
  7. Spring Boot Interview Questions
  8. Core Java Multiple Choice Questions
  9. 60 Java MCQ Questions And Answers
  10. Aricent Java Interview Questions
  11. Accenture Java Interview Questions
  12. Advanced Java Interview Questions For 5 8 10 Years Experienced
  13. Core Java Interview Questions For Experienced

22 Java Exceptions Interview Questions And Answers

1. Define the concept of “exception”

An exception is a problem (error) that occurs during program execution. Exceptions can occur in many cases, for example:

    1. User entered incorrect data.
    1. The file accessed by the program was not found.
  1. Network connection to the server was lost during data transfer. Etc.

All exceptions in Java are objects. Therefore, they can be generated not only automatically in the event of an exceptional situation, but also created by the developer.

2. What is the hierarchy of exceptions.

Exceptions are divided into several classes, but they all have a common ancestor – the Throwable class. Its descendants are subclasses of Exception and Error.

Exceptions are the result of problems in the program that are in principle solvable and predictable. For example, there was a division by zero in integers.

Errors are more serious problems that, according to the Java specification, should not be attempted to be handled in a proprietary program, since they are related to problems at the JVM level. For example, exceptions of this kind occur if the memory available to the virtual machine has run out. The program will still not be able to provide additional memory for the JVM.

In Java, all exceptions are divided into two types: controlled exceptions (checked) and unchecked exceptions (unchecked), which include errors (Errors) and run-time exceptions (Runtime Exceptions, a descendant of Exception class).

Controlled exceptions are errors that can and should be handled in the program, all descendants of the Exception class (but not RuntimeException) belong to this type.

3. Is it possible to process jvm errors?

You can handle, but you should not do it. The developer is not provided with tools for handling system and virtual machine errors.

Try Catch Finally Exception Handling Interview Questions

4. What are the ways to handle exceptions?

In Java, there are five keywords to work with exceptions:

    1. try – this keyword is used to mark the beginning of a block of code that could potentially lead to an error.
    1. catch is a keyword to mark the beginning of a block of code intended to catch and handle exceptions.
    1. finally is a keyword to mark the beginning of a block of code, which is optional. This block is placed after the last ‘catch’ block. Control is usually passed to the ‘finally’ block anyway.
    1. throw – is used to generate exceptions.
  1. throws is a keyword that is written in the method signature, and means that the method can potentially throw an exception with the specified type.

The general view of the construction for “catching” an exceptional situation is as follows:

1

2

3

4

5

6

7

8

9

try{

//here is the code that could potentially lead to an error

}

catch(SomeException e ){ //the class indicates the specific expected error

//This section describes actions to handle exceptions.

}

finally{

//executed in any case (the finally block is optional)

}

5. What does the throws keyword mean?

throws is a keyword that is written in the method signature, and means that the method can potentially throw an exception with the specified type.

6. What are the features of the finally block? Is it always performed?

When an exception is thrown, the execution of the method is sent in a non-linear path. This can be a source of problems. For example, on entering the method opens the file and closes it on exit. To prevent the file from being closed due to exception handling, a finally mechanism was proposed .

The finally keyword creates a block of code that will be executed after the try / catch block is completed , but before the code following it. The block will be executed regardless of whether an exception is passed or not. The finally operator is optional, but each try statement requires either a catch or a finally . The code in the finally block will always be executed .

7. Can there be a single catch block when catching exceptions?

Such a record is valid if there is a try {} finally {} link. But there is not much sense in such a record, yet it is better to have a catch block in which the necessary exception will be processed.

1

2

3

4

5

6

String x = “z”;

try {

  x=”234″;

} finally {

   x = “Finally”;

}

8. Could you think of a situation where the finally block will not be executed?

The finally block is not always executed, for example in this situation:

1

2

3

4

5

try {

   System.exit(0);

} catch(Exception e) {

   e.printStackTrace();

} finally { }

Here finally is unreachable, as the system exit from the program occurs. In general terms: when jvm dies, it’s not up to finally (you can come up with other examples of how to kill jvm and answer the question in the title).

9. Can a single catch block catch several exceptions (from the same and different branches of inheritance)?

In Java 7 , a new construct has become available, with which you can catch several exceptions with one catch block:

1

2

3

4

5

6

try {  

} catch( IOException | SQLException ex ) {  

 logger.log(ex);

 throw ex;

}

Java Exception Handling Interview Questions And Answers

10. What do you know about catched / uncatched exceptions?

All exceptional situations are divided into “checked” (checked) and “unchecked” (unchecked) (see the picture at the beginning of the article). This property is inherent in the “rhizome” (Throwable, Error, Exception, RuntimeException) and is inherited. Not visible in the source code of the class exception.

In the following examples, just note that — Throwable and Exception and all of their heirs (with the exception of the heirs of Error and Runtime Exception) are checked

— Error and RuntimeException and all of their heirs are unchecked

checked exception = checked by the compiler.

The topic is quite extensive in order to fit it in one answer.

  1. Checked exceptions are those that must be handled by a catch block or described in the method signature. Unchecked may not be processed or described.
  2. Unchecked exceptions in Java – inherited from RuntimeException, checked – from Exception (not including unchecked).

Checked exceptions are different from Unchecked exceptions in Java, in that:

1) Availability / handling Checked exceptions are checked at compile time . The presence / handling of Unchecked exceptions occurs at run time .

Related Java Tutorials For Beginners

Introduction to Java Programming

Java Keywords Tutorial For Beginners

Java Data Types Tutorial For Beginners

Java Operators Tutorial For Beginners

Java Control Flow Statements Tutorial

Java Performance Tuning Tips

Java Class Tutorial For Beginners

Java Exceptions Tutorial For Beginners

Java Annotations Tutorial For Beginners

Java Generics Tutorial For Beginners

Java Enumeration Tutorial For Beginners

Java Class Instance Tutorial For Beginners

11. What are the features of RuntimeException?

public class RuntimeException extends Exception – The base class for runtime errors. Refers to unhandled exceptions (uncatched \ unchecked). As stated in the class description, this is a superclass whose exceptions can be thrown during normal operation of the JVM.

12. How to write own (“user”) exception? What motives will you follow when choosing the type of an exception: checked / unchecked?

It is necessary to inherit from the base class of the required type of exceptions (for example, from Exception or RuntimeException).

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

public class ExcClass extends Exception {

   private String someString;

   public ExcClass (String string) {

       this.someString = string;

       System.out.println(“Exception ExcClass”);

   }

   public void myOwnExceptionMsg() {

       System.err.println(“This is exception massage for string: ” + someString);

   }

}

public class TestExc {

   public static void main(String[] args) {

       try {

           String s = “SomeString”;

           throw new ExcClass(s);

       } catch (ExcClass ex) {

           ex.myOwnExceptionMsg();

       }

   }

}

//Conclusion

Exception ExcClass

This is exception massage for string: SomeString

Need to be guided by the definition of the type of exception. Depending on what you want to process or see, you need and inherit from the desired class.

Java Exceptions Interview Questions And Answers For Experienced

13. Which operator allows you to forcibly throw an exception?

throw new Exception ();

14. Are there additional conditions to the method that could potentially throw an exception?

If this is a checked exception, then it must be declared in the method signature.

1

2

public void someMethod() throws Exception {

   }

15. Can the main method throw an exception to the outside, and if so, where will the exception be processed?

Maybe it will be transferred to the Java virtual machine (JVM).

16. If the return statement is contained in both the catch block and finally, which one is “superior”?

Will return from the finally block.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

   public static void main(String[] args) {

   String what =  method();

       System.out.println(what);

   }

   public static String method() {

       try {

           return “SomeString”;

       } finally {

           return “Finally message”;

       }

   }

//Conclusion

Finally message

17. What do you know about OutOfMemoryError?

OutOfMemoryError is thrown when the Java virtual machine cannot allocate (place) an object due to insufficient memory, and the garbage collector cannot free it yet.

The memory area occupied by the java process consists of several parts. The type OutOfMemoryError depends on which of them did not have enough space.

  1. java.lang.OutOfMemoryError: Java heap space

There is not enough space in the heap, namely, in the memory area in which objects created programmatically in your application are placed. The size is set by the -Xms and -Xmx parameters. If you are trying to create an object, and there is no space left in the heap, then you get this error. Typically, the problem lies in the memory leak, of which there is a great many, and the Internet is simply replete with articles on this topic.

  1. java.lang.OutOfMemoryError: PermGen space

This error occurs when there is not enough space in the Permanent area, the size of which is specified by the -XX: PermSize and -XX: MaxPermSize parameters.

  1. java.lang.OutOfMemoryError: GC overhead limit limit exceeded

This error may occur as soon as the first and second areas overflow. It is connected with the fact that there is little memory and the GC is constantly working, trying to free up some space. This error can be disabled using the -XX parameter: -UseGCOverheadLimit, but, of course, it should not be disabled, and either solve the problem of memory leakage, or allocate more volume, or change the GC settings.

  1. java.lang.OutOfMemoryError: unable to create new native thread

Thrown when it is not possible to create more threads.

18. What do you know about SQLException? What type of checked or unchecked is it, why?

SQLException provides information about database access errors or other errors associated with working with databases.

SQLException refers to checked exceptions, which means it is checked at compile time.

Disputes about this type of exception go about the fact that the developer has to constantly handle this exception in the code, although most of the errors occur during program execution, that is, in the opinion of many, it would be better to attribute it to unchecked runtime exceptions.

1

2

3

4

5

6

try {

   // make some SQL call(s)

} catch {SQLException e) {

   // log the exception

   return; // and give up

}

The Effective Java Second Edition Joshua Bloch argument is: making SQLException testable is an attempt to get developers to handle the exception and wrap it in a new level of abstraction.

Advanced Java Exception Handling Interview Questions And Answers

19. What is Error? In which case Error is used. Give an example of Error.

Errors are more serious problems that, according to the Java specification, should not be attempted to be handled in a proprietary program, since they are related to problems at the JVM level. For example, exceptions of this kind occur if the memory available to the virtual machine has run out.

For an example, look at the picture of the hierarchy of exceptions at the beginning of the article. As an example – OutOfMemoryError.

20. What construction is used in Java for exception handling?

You can use try-catch-finally and c 7th Java try-with-resources. The first way:

1

2

3

4

5

6

7

8

9

try{

//here is the code that could potentially lead to an error

}

catch(SomeException e ){ //the class indicates the specific expected error  

//This section describes actions to handle exceptions.

}

finally{

//performed in any case ( finally block is optional)

}

Try with resources:

1

2

3

4

try(here, open the file, etc.){

//…

}

//after the block the file will close automatically.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Old Way

BufferedReader br = new BufferedReader(new FileReader(path));

  try {

           return br.readLine();

       } finally {

           if (br != null) {

               br.close();

           }

       }

JDK 7

try (BufferedReader br =

               new BufferedReader(new FileReader(path)) ) {

       return br.readLine();

   }

Also see the answer to “What are the ways to handle exceptions?”

21. Suppose there is a try-finally block. An exception was thrown in the try block and the execution moved to the finally block. An exception also occurred in the finally block. Which of the two exceptions will be dropped from the try-finally block? What happens to the second exception?

The answer is similar to the case with two return – will be processed in the finally block. If two exceptions were thrown – one in try, the second in finally, then the exception in finally “swallowed” the exception above (see example). If an exception was processed before the finally block, we can get information about the exception in the try block and thus not lose the exception, which can later be overwritten in finally by another exception.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

public class TestExc {

   public static void main(String[] args) {

       Exception ex = twoExceptionsMethod();

       System.out.println(ex.getClass());

       String s = twoExceptionsMethod2();

       System.out.println(s);

   }

   public static Exception twoExceptionsMethod() {

       try {

           return new IndexOutOfBoundsException();

       } finally {

           return new NullPointerException();

       }

   }

   public static String twoExceptionsMethod2() {

       try {

           throw new NullPointerException();

       }catch (NullPointerException ex) {

           System.out.println(ex.getMessage()+ ” catch”);;

       }

       finally {

           Exception ex2 = new Exception();

           return ex2.getMessage() + “finally”;

       }

   }

}

//Conclusion

class java.lang.NullPointerException

null catchBlock

null finallyBlock

22. Suppose there is a method that can throw an IOException and a FileNotFoundException in which sequence should the catch blocks go? How many catch blocks will be executed?

The general rule is to handle exceptions from the “junior” to the senior. Those. you cannot put catch (Exception e) {} in the first block , otherwise all further catch () blocks will not be able to process anything, since any exception will fall under ExceptionName extends Exception.

Thus, you first need to handle public class FileNotFoundException extends IOException , and then IOException.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

   public static void ioExcAndFileNotFoundEx() {

       try {

           //TODO: some code

           String x = “abc”;

           if (x.equals(“abc”)) {

               throw new IOException();

           } else {

               throw new FileNotFoundException();

           }

       } catch (FileNotFoundException e) {

           e.printStackTrace();

       } catch (IOException e) {

           e.getMessage();

       }

   }

Must Read Java Interview Questions Books 2020

RELATED INTERVIEW QUESTIONS

  1. Java OOPS Interview Questions
  2. Core Java Interview Questions
  3. JSF Interview Questions
  4. JSP Interview Questions
  5. JPA Interview Questions
  6. Spring Framework Interview Questions
  7. Spring Boot Interview Questions
  8. Core Java Multiple Choice Questions
  9. 60 Java MCQ Questions And Answers
  10. Aricent Java Interview Questions
  11. Accenture Java Interview Questions
  12. Advanced Java Interview Questions For 5 8 10 Years Experienced
  13. Core Java Interview Questions For Experienced
  14. GIT Interview Questions And Answers
  15. Network Security Interview Questions
  16. CheckPoint Interview Questions
  17. Page Object Model Interview Questions
  18. Apache Pig Interview Questions
  19. Python Interview Questions And Answers
  20. Peoplesoft Integration Broker Interview Questions
  21. PeopleSoft Application Engine Interview Questions
  22. RSA enVision Interview Questions
  23. RSA SecurID Interview Questions
  24. Archer GRC Interview Questions
  25. RSA Archer Interview Questions
  26. Blockchain Interview Questions
  27. Commvault Interview Questions
  28. Peoplesoft Admin Interview Questions
  29. ZooKeeper Interview Questions
  30. Apache Kafka Interview Questions

Leave a Comment