Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Showing posts with label EXCEPTION HANDLING. Show all posts
Showing posts with label EXCEPTION HANDLING. Show all posts

Wednesday, 28 June 2017

Custom Exception In Java


Java Custom Exception


Custom Exception In Java

Java custom exception means to create your own exception. You can create your own exception in java which is called custom exception or user-defined exception.

You can create your own exception and massages by the help of custom exception.

Let's create simple example of custom exception

Java Custom Exception Example

This is a simple custom example where we will throw own exception.

There we will create 2 files.

//File 1 : InvalidAgeException.java

class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}

//File 2 : CustomExceptionExample.java

class CustomExceptionExample
{
static void validate(int age)throws InvalidAgeException
{
if(age < 18)
{
throw new InvalidAgeException("not valid age");
}
else
{
System.out.println("age is valid for vote");
}
}
public static void main(String args[])
{
try
{
validate(10);
}
catch(Exception e)
{
System.out.println("Exception is " +e);
}
}
}

save : InvalidAgeException.java, CustomExceptionExample.java
compile : CustomeExceptionExample.java
run : CustomeExceptionExample

output : Exception is InvalidAgeException : not valid age


In java Exception Handling, there are two types of exception :

  • checked exception : Checked exception are the exception which is checked at compile-time by the compiler is called checked exception e.g IOException, SQLException, FileNotFoundException .
  • unchecked exception : Unchecked exception are the exception which is not checked at compile-time , it is checked at run-time is called unchecked exception e.g ArithmeticException, NullPointerException, NumberFormatException, etc.

Custom Checked Exception

If the customer is able to recover from the exception, make it checked exception. When you create custom checked exception, extends java.lang.Exception.

//File 1 : NameNotFoundException.java

class NameNotFoundException extends Exception
{
NameNotFoundException(String s)
{
super(s);
}
}

//File 2 : CustomerService.java

class CustomerService
{
Customer findByName(String name)throws NameNotFoundException
{
if("".equals(name))
{
throw new NameNotFoundException("name is empty");
}
return new Customer(name);
}
public static void main(String args[])
{
CustomerService cs = new CustomerService();
{
try
{
Customer c = cs.findByName("");
}
catch(NameNotFoundException n)
{
e.printStackTrace();
}
}
}
}

Share:

Tuesday, 13 June 2017

Java Throws

 

Java Throws Keyword

Java Throws

Throws is a keyword in java which is used to declare an exception in our java program. Throws keyword gives the information to the programmer that there may occur an exception so that programmer can take good decision for maintain the normal flow of the program.

Throws keyword make a java programs handler free.

With Throws keyword we can declare only checked exception like SQLException, IOException, etc.


Advantage of Throws Keyword

  • Throws keyword aware the programmer that there may occur exception so it better for the programmer to provide the exception handling code.
  • Throws keyword make program handler free.
  • Throws keyword is also used for forwarding checked exception in calling chain because by default unchecked exception are forwarded in calling chain.

Some Points About Throws Keyword

  1. Throw keyword inform the programmer about an exception.
  2. Throws keyword are used with the method signature(end of the method).
  3. We can declare only checked exception with throws keyword because unchecked exception can be handled by the programmer.

Syntax of Throws Keyword

return_type method_name()throws Exception_Class_Name{
}


Java Throws Example

In this example we will learn how to apply throws keyword with method and how to forward(propagated) checked exception in calling chain.

import java.io.IOException;
class ThrowsExample
{
void a()throws IOException 
{
throw new IOException("device error");//checked Exception
}
void b()throws IOException
{
a();
}
void c()
{
try
{
b();
}
catch(Exception e)
{
System.out.println("Exception is handled");
}
}
public static void main(String args[])
{
ThrowsExample t = new ThrowsExample();
t.c();
}
}

output : Exception is handled

Note : if you calling a method that declares an exception, you must either caught or declare an exception.



Java Throws Example 1

Case1 : In case you handle the exception,  code will execute fine whether exception occurs during the program or not.

import java.io.*;
class A
{
void b()throws IOException
{
throw new IOException("device error");
}
}
class Test
{
public static void main(String args[])
{
try
{
A a = new A();
a.b();
}
catch(Exception e)
{
System.out.println("Exception is handled");
}
}
}

output : Exception is handled

Case2 : (a) In case you declare the exception , if exception doesn't occur, the code will be execute fine.


import java.io.*;
class A
{
void b()throws IOException
{
System.out.println(" welcome");
}
}
class Test
{
public static void main(String args[])throws IOException
{
A a = new A();
a.b();
}

}

output : welcome

(b) if exception occurs


import java.io.*;
class A
{
void b()throws IOException
{
throw new IOException("device error");
}
}
class Test
{
public static void main(String args[])throws IOException
{
A a = new A();
a.b();
}


}

output : Exception in thread "main" java.io.IOException : device error


Difference Between Throw and Throws

There are some difference between throw and throws keyword in java exception handling.

Throw
  • Throw keyword are used to explicitly throw an exception.
  • Throw keyword are used within the method.
  • We cannot propagate or forward checked exception in calling chain through throw keyword. 
Throws
  • Throws keyword are used to declare an exception.
  • Throws keyword are used with the method signature, not within method body  like throw keyword.
  • By using Throws keyword we can easily propagate or forward a checked exception in calling chain.



Share:

Wednesday, 17 May 2017

Java Throw Keyword In Exception Handling

 Throw

throw

Java throw is a keyword in java, Which is used to throw an exception explicitly and used with the mostly custom exception.

In java, We have many predefined exceptions like ArithmeticException, ArrayIndexOutOfBoundsException but programmers can create a new exception and throw it explicitly. These exceptions are called user-defined exception. By the help of throw keyword in exception handling we can throw user defined exception in java.

By the help of throw keyword, we can throw both checked and unchecked exception in java. Java throw keyword is mainly used to throw custom exceptions.

Syntax of throw keyword 

throw exception;


Java throw Keyword Example

This is a very simple example of java throw keyword. In this example we will check the candidate's age is 18 or not, if he will less than 18 we will throw an ArithmeticException otherwise welcome to vote.

class ThrowKeywordExample
{
public void check(int age)
{
if(age<18)
{
throw new ArithmeticException("Age is not valid");
}
else
{
System.out.println("Your welcome to vote");
}
}
public static void main(String args[])
{
ThrowKeywordExample t = new ThrowKeywordExample();
t.check(11);
}
}

output : Exception in thread "main" java.lang.ArithmeticException : Age is not valid.

Note : throw keyword is always used within a method body.


Another throw Example 

class AnotherExampleOfThrow
{
static int sum(int num1, int num2)
{
if(num1 == 0)
{
throw new ArithmeticException("parameter first is not valid");
}
else
{
System.out.println("both parameter are correct");
return num1 + num2;
}
}
public static void main(String args[])
{
int result = sum(0,10);
System.out.println(result);
System.out.println("continue next statements");
}
}

output : Exception in thread "main" java.lang.ArithmeticException : parameter first is not valid.



Exception Propagation 

In exception propagation, An exception thrown from the top of the stack and if it is not caught, its drops down the call stack to the previous method, and again if not caught there , the exception again drops down to the previous method and so on until they are caught.

Example of Exception Propagation in Java

class ExampleOfEP
{
void a()
{
int i = 30/0;//Exception Occurred
}
void b()
{
a();
}
void c()
{
try
{
b();
}
catch(Exception e)
{
System.out.println("Exception Handled");
}
}
public static void main(String args[])
{
ExampleOfEP ee = new ExampleOfEP();
ee.c();
}


output : Exception Handled

In the above example, Exception are occurred in method a() and it is not handled here so it is propagated to method b() and here it not handled, so it is propagated to  method c where this exception is handled easily.

Exception can be handled in any method even in main method.

Note : Unchecked Exceptions are forwarded in calling chain by default.


By default checked Exception are not forwarded in calling chain

By default checked exceptions are not forwarded in calling chain but we can forward checked exception in calling chain through throws keyword. We will learn throws keyword in later.

This below example, give compilation error because checked exception cannot be forwarded in calling chain.


class Test
{
void a()
{
throw new java.io.IOException("device error");//Checked Exception
}
void b()
{
a();
}
void c()
{
try
{
b();
}
catch(Exception e)
{
System.out.println("Exception Handled");
}
}
public static void main(String args[])
{
Test ee = new Test();
ee.c();
}

Share:

Wednesday, 3 May 2017

Java Finally

 

Java Finally Block

Finally block is the mostly asked question in the interviews. 

Finally is a block in java exception handling concept. Java finally block is used to execute important java code such as stream, closing connection, closing any file etc.

Java finally block is always executed.

Java finally block is always executed whether exception is occur or not.

Java finally block is always executed whether exception is handled or not.

The main use of java finally block is clean up code.


Some Important Points About Finally Block

  1. Java finally block is always executed.
  2. Java finally never used to catch any exception in java.
  3. Now you can have a try block with only finally block without catch block.
  4. If you are having a finally block with a catch block then it must be the last block. finally block cannot be used between try and catch block.
  5. Finally block is an optional block.
  6. You can use multiple catch block with single try block but you can use only one finally block with single try.

Let's take look in below diagram how to executes finally block in different cases.

Java Finally

Syntax of finally block 1 :

Syntax of finally block only with try block.

try
{
//statements
}
finally
{
//statements
}

Syntax of finally block 2 :

Syntax of finally block with try and catch both.

try
{
//statements
}
catch
{
//statements 
}
finally
{
//statements
}


Java Finally Block Examples

Case 1

Java finally block with only try and exception is not occurred here.

class FinallyExample1
{
public static void main(String args[])
{
try
{
System.out.println("this is try block");
}
finally
{
System.out.println("finally block always executed");
}
}
}

output : this is try block
              finally block always executed

Case 2

Java finally with try and catch block but here exception is occurred but not handled.

class FinallyExample2
{
public static void main(String args[])
{
try

{
int a = 25/0;
System.out.println(a);
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println(ae);
}
finally
{
System.out.println("finally always executed");
}
}
}

output : finally always executed
              Exception in thread "main" java.lang.......

Case 3

Finally block with try and catch where exception is occurred in try block and caught in catch block.

class FinallyExample3
{
public static void main(String args[])
{
try

{
System.out.println("try block");
int a = 25/0;
System.out.println(a);
}
catch(ArithmeticException e)
{
System.out.println("catch block");
System.out.println(e);
}
finally
{
System.out.println("finally always executed");
}
}
}

output : try block
              catch block
              java.lang.AithmeticException: / by zero
              finally always executed
         


Return Statement and Finally Block Example

class FinallyWithReturnStatement
{
public static int show()
{
try
{
return 100;
}
finally
{
System.out.println("this is finally block");
}
}
public static void main(String args[])
{
System.out.println(FinallyWithReturnStatement.show());
}
}

output : this is finally block
              100


When Finally Block Does not execute

Finally block code will not execute 
  • if the thread is dead.
  • if you calling System.exit() method in program.
  • if exception is occurred in finally block.
For example :

Let's take 3 point , If exception occurred in finally block.

class FinallyDoesNotExecute
{
public static void main(String args[])
{
try
{
System.out.println("try block");
}
finally
{
int i = 32/0;
System.out.println("finally block will not execute");
}
}
}



Share:

Tuesday, 11 April 2017

Java Try Catch

 Java try catch block

Java try-catch block is a handler which is used to handle the exception in java programs. In java exception handling try and catch is a block which maintains the normal flow of the program.

It most important topic in exception handling concept for interview. And try and catch block is mostly used in every program when we connect to the database.


Java try catch

try Block in Java

In java try block we write all the statements or code that might throw an exception. In other words, java try block contains problematic statements.

Java try block must be used within the method.

Java try block must be followed by catch block or finally block or both blocks.

Syntax try block with catch block :

try
{
//Statements that might throw an exception
}
catch(Exception_class_Name e)
{}

Syntax try block with finally block :

try
{
//Statements that might throw an exception 
}
finally
{}


catch Block in Java

Java catch block must be associated with try block. Java catch block is used to handle the exception. Java catch block must be used after try block only. You can use single or multiple catch block with single try block in java.

Syntax catch block :

try
{
//Statements that might throw an exception
}
catch(Exception_class_Name1 e)
{}
catch(Exception_class_Name2 ee)
{}


Program Without ExceptionHandling(without try and catch)

In the below example we are not going to use try and catch block. Let's see what happens.

class WithoutTryCatchExample
{
public static void main(String args[])
{
int a = 5/0;//Exception occurs
System.out.println("this will not print");
}


output :  Exception in thread "main" java.lang.ArithmeticException :/ by zero

In the above example, the statement "this will not print" will not execute because an exception occurs before this statements. If the exception occurs at any statement, rest of the statement will not execute.


Program with ExceptionHandling(with try and catch)

Solution of the above example is here. In this example, we are going to use try and catch handler to try to catch the exception and execute the statement.

class TryAndCatchExample
{
public static void main(String args[])
{
try
{
int a = 10/0;//ArithmeticException occurs 
}
catch(ArithmeticException e)
{
System.out.println(e);
System.out.println("this will print");
}
}


output: java.lang.ArithmeticException: / by zero

             this will print


Internal working of try-catch block

First JVM checks whether the exception is handled or not, if an exception is not handled then JVM provide default handler that performs some task. These are
  • Print exception description
  • Print the stack trace
  • Causes the program to terminate 
If the exception is handled by the programmer, the normal flow of the application is maintained and all the statement will execute normally.

Java Multi catch block

As we know, we can use multiple catch block with a single try block. Java multi-catch block is used to perform the different-different task at the occurrence of the different-different exception. 

class MultiCatchBlock
{
public static void main(String args[])
{
try
{
int b[] = new int[5];
b[5] = 20/0;
}
catch(ArithmeticException ae)
{
System.out.println("Task First");
}
catch(ArrayIndexOutOfBoundsException a)
{
System.out.println("Task Second");
}
catch(Exception e)
{
System.out.println("Big Task");
}
}


output : Task First

For example 2 :

class MultiCatchBlock
{
public static void main(String args[])
{
try
{
int b[] = new int[5];
b[5] = 20/0;
}
catch(Exception e)
{
System.out.println("Big Task");
}
catch(ArithmeticException ae)
{
System.out.println("Task First");
}
catch(ArrayIndexOutOfBoundsException a)
{
System.out.println("Task Second");
}
}


output: compile time error

Some Points about catch block

  • Only one exception occurred at a time and at a time only one block is executed.
  • All catch block in java must be ordered from most specific to most general i.e catch for ArithmeticException comes before catch for Exception.
Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Link

Translate