Skip to main content

throw exception in java

throw Exception in Java

In java we have already defined exception classes such as ArithmeticException ArrayIndexOutOfBoundsException NullPointerException etc. There are certain conditions defined for these exceptions and on the occurrence of those conditions they are implicitly thrown by JVM(java virtual machine).

throw an already defined exception like ArithmeticException,IOException etc.

Syntax of throw statement

throw AnyThrowableInstance;
Example:
//A void method
public void sample()
{
   //Statements
   //if (somethingWrong) then
   IOException e = new IOException();
   throw e;
   //More Statements
 }
Note :
  • A call to the above mentioned sample method should be always placed in a try block as it is throwing a checked exception – IOException. This is how it the call to above method should be done:
    MyClass obj =  new MyClass();
    try{
          obj.sample();
    }catch(IOException ioe)
     {
          //Your error Message here
          System.out.println(ioe);
      }
  • Exceptions in java are compulsorily of type Throwable. If you attempt to throw an object that is not throwable, the  compiler refuses to compile your program and it would show a compilation error.
Flow of execution while throwing an exception using throw keyword
Whenever a throw statement is encountered in a program the next statement doesn’t execute. Control immediately transferred to catch block to see if the thrown exception is handled there. If the exception is not handled there then next catch block is being checked for exception and so on. If none of the catch block is handling the thrown exception then a system generated exception message is being populated on screen, same what we get for un-handled exceptions.
E.g.
class ThrowExample{
   public static void main(String args[]){
      try{
    char array[] = {'a','b','g','j'};
    /*I'm displaying the value which does not
     * exist so this should throw an exception
     */
    System.out.println(array[78]);
      }catch(ArithmeticException e){
     System.out.println("Arithmetic Exception!!");
       }
   }
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 
78 at.ThrowExample.main(Details.java:9)
Since the exception thrown was not handled in the catch blocks the system generated exception message got displayed for that particular exception.

Few examples of throw exception in Java

1: How to throw your own exception explicitly using throw keyword

class MyOwnException extends Exception {
   public MyOwnException(String msg){
      super(msg);
   }
}

class EmployeeTest {
   static void  employeeAge(int age) throws MyOwnException{
      if(age < 0)
         throw new MyOwnException("Age can't be less than zero");
      else
         System.out.println("Input is valid!!");
   }
   public static void main(String[] args) {
       try {
            employeeAge(-2);
       }
       catch (MyOwnException e) {
            e.printStackTrace();
       }
   }
}
Output:
MyOwnException: Age can't be less than zero
Points to Note : Method call should be in try block as it is throwing an exception.

2: How to throw an already defined exception using throw keyword

class Exception2{
   static int sum(int num1, int num2){
      if (num1 == 0)
         throw new ArithmeticException("First parameter is not valid");
      else
         System.out.println("Both parameters are correct!!");
      return num1+num2;
   }
   public static void main(String args[]){
      int res=sum(0,12);
      System.out.println(res);
      System.out.println("Continue Next statements");
   }
}
Output:
Exception in thread main java.lang.ArithmeticException: First parameter is not valid
Similarly other exceptions, such as NullPointerException,ArrayIndexOutOfBoundsException etc. can be thrown. That’s all for the topic how to throw exception in java. Let me know your feedback on this.

Comments

Popular posts from this blog

Switch Case

Syntax : Switch Case in Java Programming It is alternative to else-if ladder. Switch Case Syntax is similar to – C/C++  Switch. Switch allows you to choose a block of statements to run from a selection of code, based on the return value of an expression. The expression used in the switch statement must return an  int, a String, or an enumerated value . switch (selection) { // value case value1 : // checking value 1 statement ( s ) ; break ; // use to break switch flow if condition match case value2 : // checking value 2 statement ( s ) ; break ; . . case value_n : statement ( s ) ; break ; default : statement ( s ) ; } Different Ways of Using Switch Case : Switch Case Using Integer Case int i=3; switch (i) { case 1 : System . out . println ( "One player is playing this game." ) ; break ; case 2 : System . out . println ( "Two players are playing ...

Inheritance in Java

Inheritance in Java Inheritance  is one of the feature of Object-Oriented Programming (OOPs). Inheritance allows a class to use the properties and methods of another class. In other words, the derived class inherits the states and behaviors from the base class. The derived class is also called subclass and the base class is also known as super-class . The derived class can add its own additional variables and methods. These additional variable and methods differentiates the derived class from the base class. Inheritance is a  compile-time  mechanism. A super-class can have any number of subclasses . But a subclass can have only one superclass. This is because Java does not support multiple inheritance. The superclass and subclass have  “is-a”  relationship between them. Let’s have a look at the example below. Inheritance  Example Let’s consider a superclass  Vehicle . Different vehicles have different features and properties howeve...

Multilevel inheritance

Multilevel inheritance We discussed a bit about  Multilevel inheritance  in types of inheritance in java. In this tutorial we will explain multilevel inheritance with the help of   diagram  and  example program . It’s pretty clear with the diagram that in Multilevel inheritance there is a concept of grand parent class. If we take the example of above diagram then class C inherits class B and class B inherits class A which means B is a parent class of C and A is a parent class of B. So in this case class C is implicitly inheriting the properties and method of class A along with B that’s what is called multilevel inheritance. Example : In this example we have three classes –  Car, Maruti and Maruti800. We have done a setup – class Maruti extends Car and class Maurit800 extends Maurti. With the help of this Multilevel hierarchy setup our Maurti800 class is able to use the methods of both the classes (Car and Maruti). class Car { ...