Core Java Tutorials


Introduction

Java Hello World

Java Compilation

JDK New Features

JVM Architecture

Java OOPs Concepts

Java Package

Array

Exception Handling

String

Immutable Class

File Handling

Serialization

MultiThreading

Volatile

Concurrent Package

Collection

Collection Internal

Generics

Cloning

Reflection In Java

Annotation

Class Loader

Java Inner classes

Garbage Collector

JDBC

References In Java

Heap Dump & Thread Dump

Keywords In Exception Handling

Java provides specific 5 keywords for exception handling. which are given below:-

try
catch
finally
throw
throws

 try block

The try block contains a block of program statements where an exception might occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must followed by a catch block or finally block or both.

Syntax of try block

try{

   //statements that may accur exception  
}

Catch Block

A catch block must be associated with a try block. the catch block executes only if an exception of a particular type occurs within the try block. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception or it's parent class exception executes.

Syntax of Catch block

try{

  //statements that may occur exception  
}
catch (Exception e){

  //Exception handling code
}

Finally Block

finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not.

Syntax of Finally block with try block

try{

  //statements that may occur exception  
}
finally {

  //Statement to be executed
}

Syntax of Finally block with try-catch block

try{

  //statements that may occur exception  
}
catch (Exception e){

  //Exception handling code
}
finally {

  //Statement to be executed
}

Throws Keywords

In java we can handle Exception in two way's. Either the code is being enclosed by try block and exception handling is implemented in the same method, or the method can throws the exception to the calling method simply. This is what ‘throws’ does in exception handling, it throws the exception to immediate calling method in the hierarchy. The throws keyword appears at the end of a method's signature.

Syntax of handle exception with Throws keyword

public class ThrowException{

	public void myException() Throws Exception{
	  
}

Throw Keywords

throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception.

Syntax of throw an exception explicitly

public class ThrowException{

	public void myException(){
	  throw new IOException();
}