[Java] Exception

Back-End/Java_1 2016. 5. 18. 15:30
donaricano-btn

Exception

- An exception is an event, which occurs during the execution of a program, that interrupts the normal flow of the program

- The Throwable class is the superclass of all errors and exceptions in the java language

- Exceptions can be handled by using 'try-catch' block

- If a method doesn't handle the exception, then it is mandatory to specify the exception type in the method signature using 'throws' clause

- We can explicitly throw an exception using 'throw' clause


1. How Exception terminates java program

whenever exception arises, it terminates the program execution, means it stops the execution of the current java program


2. Handling

Exceptions can be handled by using "try-catch" block


3. Throws

The throws clause in java programming language is belongs to a method to specify that the method raises particular type of exception while being executed

Anybody calling a method with a throws clause is needed to be enclosed within the try catch blocks


4. Throw

Use 'throw' statement to throw an exception or simply use the throw clause with an object reference to throw an excpetion

The syntax is 'throw new Exception();' Even you can pass the error message to the Exception constructor


5. Multiple Catch Blocks

A single try blocks can have multiple catch blocks. This is required when the try block has statements that generates different types of exceptions

If the first catch block contains the Exception class object then subsequent catch blocks are never executed

The last catch block in multiple catch blocks must contain the Exception class object.

This is because, the java compiler gives an error saying that the subsequent catch blocks haven't been reached. This is known as Unreachable code problem


6. Finally

- The finally block always executes immediately after try-catch block exits

The finally block is executed incase even if an unexpected exception occurs

The main usage of finally block is to do clean up job

The runtime system always executes the code within the finally block regardless of what happens in the try block, so it is the ideal place to keep cleanup code


7. Without Catch

- You can handle exception still without having catch blocks also, only thing you need to do is declare the throws clause in your method signature, so that the calling function would handle the exception, Before throwing exception, it executes the finally block


8. Custom Exception

Sometimes it is required to develop meaningful exceptions based on application requirements. We can create our own exceptions by extending 'Exception' class



'Back-End > Java_1' 카테고리의 다른 글

[Java] JVM  (0) 2016.06.03
[Java] JDK, JRE, and JVM  (0) 2016.06.03
[Java] Constructor  (0) 2016.05.17
[Java] Enum  (0) 2016.05.13
[Java] Array  (0) 2016.05.12
블로그 이미지

리딩리드

,