Wednesday, 23 December 2020

Java learnings - Intro, Variables, data types & Operators

 

Introduction to Java programming

JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It was developed by James Gosling and Patrick Naughton. It is a simple programming language.  Writing, compiling and debugging a program is easy in java.  It helps to create modular programs and reusable code.


Java terminology

Before we start learning Java, lets get familiar with common java terms.

Java Virtual Machine (JVM)
This is generally referred as JVM. Before, we discuss about JVM lets see the phases of program execution. Phases are as follows: we write the program, then we compile the program and at last we run the program.
1) Writing of the program is of course done by java programmer like you and me.
2) Compilation of program is done by javac compiler, javac is the primary java compiler included in java development kit (JDK). It takes java program as input and generates java bytecode as output.
3) In third phase, JVM executes the bytecode generated by compiler. This is called program run phase.

So, now that we understood that the primary function of JVM is to execute the bytecode produced by compiler. Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. That is why we call java as platform independent language.

bytecode

As discussed above, javac compiler of JDK compiles the java source code into bytecode so that it can be executed by JVM. The bytecode is saved in a .class file by compiler.

Java Development Kit(JDK)
While explaining JVM and bytecode, I have used the term JDK. Let’s discuss about it. As the name suggests this is complete java development kit that includes JRE (Java Runtime Environment), compilers and various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program you would need JDK installed on your computer.

Java Runtime Environment(JRE)
JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed on your system, you can run a java program however you won’t be able to compile it. JRE includes JVM, browser plugins and applets support. When you only need to run a java program on your computer, you would only need JRE.

Main Features of JAVA

Java is a platform independent language

Compiler(javac) converts source code (.java file) to the byte code(.class file). As mentioned above, JVM executes the bytecode produced by compiler. This byte code can run on any platform such as Windows, Linux, Mac OS etc. Which means a program that is compiled on windows can run on Linux and vice-versa. Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. That is why we call java as platform independent language.

Java is an Object Oriented language

Object oriented programming is a way of organizing programs as collection of objects, each of which represents an instance of a class.

4 main concepts of Object Oriented programming are:

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

Simple

Java is considered as one of simple language because it does not have complex features like Operator overloading, Multiple Inheritance, pointers and Explicit memory allocation.

Robust Language

Robust means reliable. Java programming language is developed in a way that puts a lot of emphasis on early checking for possible errors, that’s why java compiler is able to detect errors that are not easy to detect in other programming languages. The main features of java that makes it robust are garbage collection, Exception Handling and memory allocation.

Secure

We don’t have pointers and we cannot access out of bound arrays (you get ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several security flaws like stack corruption or buffer overflow is impossible to exploit in Java.

Java is distributed

Using java programming language we can create distributed applications. RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for creating distributed applications in java. In simple words: The java programs can be distributed on more than one systems that are connected to each other using internet connection. Objects on one JVM (java virtual machine) can execute procedures on a remote JVM.

Multithreading

Java supports Multithreading. Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilisation of CPU.

Portable

As discussed above, java code that is written on one machine can run on another machine. The platform independent byte code can be carried to any platform for execution that makes java code portable.

Working strategy:

Source Code --> complier --> Byte code --> JVM <-->Interpreter for Windows/Mac/Linux

.java file -->javac-->.class file

javac compiler takes java program (.java file containing source code) and translates it into machine code (referred as byte code or .class file).

Java Virtual Machine (JVM) is a virtual machine that resides in the real machine (your computer) and the machine language for JVM is byte code

JVM executes the byte code generated by compiler and produce output. JVM is the one that makes java platform independent.    

Each operating system has different JVM, however the output they produce after execution of byte code is same across all operating systems

So to summarize everything: The Java Virtual machine (JVM) is the virtual machine that runs on actual machine (your computer) and executes Java byte code. The JVM doesn’t understand Java source code, that’s why we need to have javac compiler that compiles *.java files to obtain *.class files that contain the byte codes understood by the JVM. JVM makes java portable (write once, run anywhere). Each operating system has different JVM, however the output they produce after execution of byte code is same across all operating systems.

JVM Vs JRE Vs JDK

JRE: JRE is the environment within which the java virtual machine runs. JRE contains Java virtual Machine(JVM), class libraries, and other files excluding development tools such as compiler and debugger.
Which means you can run the code in JRE but you can’t develop and compile the code in JRE.

JVM: As we discussed above, JVM runs the program by using class, libraries and files provided by JRE.

JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler, debugger etc.

Keypoints:

JRE = JVM + Jar files(Lib and complied class files)

JDK = JRE + Complier, debugger and other development tools


First Java Program

public class Classname{
public statis void main(String[] args){
System.out.print("First program I am executing");
}


Public: This makes the main method public that means that we can call the method from outside the class.

static: We do not need to create object for static methods to run. They can run itself.

void: It does not return anything.

main: It is the method name. This is the entry point method from which the JVM can run your program.

(String[] args): Used for command line arguments that are passed as strings. 


Variables

·         A variable is a container which holds the value while the Java program is executed.

·         A variable is assigned with a data type.

·         Variable is a name of memory location.

·         There are three types of variables in java: local, instance and static.

·         There are two types of data types in Java: primitive and non-primitive.

·         Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It is a combination of "vary + able" that means its value can be changed.

 

How to Declare a variable in Java

To declare a variable follow this syntax:

data_type variable_name = value;

here value is optional because in java, you can declare the variable first and then later assign the value to it.

Eg:

char ch = 'A';

int number = 100;

 

Variables naming convention in java

1) Variables naming cannot contain white spaces, for example: int num ber = 100; is invalid because the variable name has space in it.

2) Variable name can begin with special characters such as $ and _

3) As per the java coding standards the variable name should begin with a lower case letter, for example int number; For lengthy variables names that has more than one words do it like this: int smallNumber; int bigNumber;

4) Variable names are case sensitive in Java.

5) Reserved words (like Java keywords, such as int or boolean) cannot be used as names

 

Types:

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

 

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called instance variable. It is not declared as static.

It is called instance variable because its value is instance specific and is not shared among instances.

 

3) Static variable

A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of static variable and share among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory.

 

Eg:

class A{ 

int data=50;//instance variable 

static int m=100;//static variable 

void method(){ 

int n=90;//local variable 

} 

}//end of class

 

 

Data Types in Java

 

Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:

 

Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.

Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

 

Data Type & size

Default Value

Description

byte       1 byte

0             

Stores whole numbers from -128 to 127

short     2 bytes

0             

Stores whole numbers from -32,768 to 32,767

int           4 bytes

0             

Stores whole numbers from -2,147,483,648 to 2,147,483,647

long       8 bytes

0             

Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

float       4 bytes

0.0f

Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double  8 bytes

0.0d

Stores fractional numbers. Sufficient for storing 15 decimal digits

Boolean 1 bit

False

Stores true or false values

char 2 bytes

'\u0000’

Stores a single character/letter or ASCII values

               

Point to note:

why char uses 2 byte in java and what is \u0000 ?

It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of Unicode system.

 

Primitive number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are byte, short, int and long. Which type you should use, depends on the numeric value.

 

Floating point types represents numbers with a fractional part, containing one or more decimals. There are two types: float and double.

 

Non-Primitive Data Types

Non-primitive data types are called reference types because they refer to objects.

 

The main difference between primitive and non-primitive data types are:

Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is not defined by Java (except for String).

Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.

A primitive type has always a value, while non-primitive types can be null.

A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.

The size of a primitive type depends on the data type, while non-primitive types have all the same size.

Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc

 

 

Type Casting

 

Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

 

Widening Casting (automatically) - converting a smaller type to a larger type size

byte -> short -> char -> int -> long -> float -> double

 

Narrowing Casting (manually) - converting a larger type to a smaller size type

double -> float -> long -> int -> char -> short -> byte

 

public class Main {

  public static void main(String[] args) {

    int myInt = 9;

    double myDouble = myInt; // Automatic casting: int to double

 

    System.out.println(myInt);      // Outputs 9

    System.out.println(myDouble);   // Outputs 9.0

  }

}

 

public class Main {

  public static void main(String[] args) {

    double myDouble = 9.78;

    int myInt = (int) myDouble; // Manual casting: double to int

 

    System.out.println(myDouble);   // Outputs 9.78

    System.out.println(myInt);      // Outputs 9

  }

}

 

Operators

Operator Type

Category

Precedence                                

Unary

postfix

expr++ expr--

prefix

++expr --expr +expr -expr ~ !

Arithmetic

multiplicative

* / %

additive

+ -

Shift

shift

<< >> >>>

Relational

comparison

< > <= >= instanceof

equality

== !=

Bitwise

bitwise AND

&

bitwise exclusive OR

^

bitwise inclusive OR

|

Logical

logical AND

&&

logical OR

||

Ternary

ternary

? :

Assignment

assignment

= += -= *= /= %= &= ^= |= <<= >>= >>>=

 

class Unary OperatorExample{ 

public static void main(String args[]){ 

int a=10; 

int b=10; 

System.out.println(a++ + ++a);//10+12=22 

System.out.println(b++ + b++);//10+11=21 

}} 

 

int a=10; 

int b=-10; 

boolean c=true; 

boolean d=false; 

System.out.println(~a);//-11 (minus of total positive value which starts from 0) 

System.out.println(~b);//9 (positive of total minus, positive starts from 0) 

System.out.println(!c);//false (opposite of boolean value) 

System.out.println(!d);//true

 

Arithmetic

int a=10; 

int b=5;  

System.out.println(a+b);//15 

System.out.println(a-b);//5 

System.out.println(a*b);//50 

System.out.println(a/b);//2 

System.out.println(a%b);//0 

 

Shift Operator

 

The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.

 

class LeftShiftOperatorExample{ 

public static void main(String args[]){ 

System.out.println(10<<2);//10*2^2=10*4=40 

System.out.println(10<<3);//10*2^3=10*8=80 

System.out.println(20<<2);//20*2^2=20*4=80 

System.out.println(15<<4);//15*2^4=15*16=240 

}} 

 

The Java right shift operator >> is used to move left operands value to right by the number of bits specified by the right operand.

 

class RightShiftOperatorExample{ 

public static void main(String args[]){ 

System.out.println(10>>2);//10/2^2=10/4=2 

System.out.println(20>>2);//20/2^2=20/4=5 

System.out.println(20>>3);//20/2^3=20/8=2 

}} 

 

 

//For positive number, >> and >>> works same 

    System.out.println(20>>2); 

    System.out.println(20>>>2); 

    //For negative number, >>> changes parity bit (MSB) to 0 

    System.out.println(-20>>2); 

    System.out.println(-20>>>2); 

 

5

5

-5

1073741819

 

Logical && vs Bitwise &

 

The logical && operator doesn't check second condition if first condition is false. It checks second condition only if first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.

 

int a=10; 

int b=5; 

int c=20; 

System.out.println(a<b&&a++<c);//false && true = false 

System.out.println(a);//10 because second condition is not checked 

System.out.println(a<b&a++<c);//false && true = false 

System.out.println(a);//11 because second condition is checked

 

Logical || and Bitwise |

 

int a=10; 

int b=5; 

int c=20; 

System.out.println(a>b||a<c);//true || true = true 

System.out.println(a>b|a<c);//true | true = true 

//|| vs | 

System.out.println(a>b||a++<c);//true || true = true 

System.out.println(a);//10 because second condition is not checked 

System.out.println(a>b|a++<c);//true | true = true 

System.out.println(a);//11 because second condition is checked 

 

Java Ternary Operator

Java Ternary operator is used as one liner replacement for if-then-else statement and used a lot in Java programming. it is the only conditional operator which takes three operands.

int a=2; 

int b=5; 

int min=(a<b)?a:b; 

System.out.println(min); 

 

 

Java Assignment Operator

Java assignment operator is one of the most common operator. It is used to assign the value on its right to the operand on its left.

 

Example

int a=10; 

int b=20; 

a+=4;//a=a+4 (a=10+4) 

b-=4;//b=b-4 (b=20-4) 

System.out.println(a); 

System.out.println(b);

 

 

int a=10; 

a+=3;//10+3 

System.out.println(a); 

a-=4;//13-4 

System.out.println(a); 

a*=2;//9*2 

System.out.println(a); 

a/=2;//18/2 

System.out.println(a);

 

13

9

18

9

 

short a=10; 

short b=10; 

//a+=b;//a=a+b internally so fine 

a=a+b;//Compile time error because 10+10=20 now int 

System.out.println(a); 

 

so,

a=(short)(a+b);//20 which is int now converted to short 


Wednesday, 16 December 2020

Java learnings - Exception Handling

 

What is Exception?

Exception in Java is used to handle errors or any other exceptional event that occurs in the normal flow of a program. There are several way Exception can occur in Java.

Data provided is not in expected format(eg. int instead of String).

DB cannot be connected.

Network connection Lost.

An object is null.

 

Exception hierarchy

Exception and Error are two different classes that derived from Throwable.

Errors represent a situation which doesn’t occur because of Programming error but that might happen at the time of program execution and these are abnormal behavior which java program cannot handle and shouldn’t bother to handle. JVM running out of memory is a type of Error which can occur at runtime.

 

Object

 


Throwable

 

Exceptions                           Error

 

Checked Exception                      Virtual machine error 

Unchecked Exception                                                                                                                                                                                         Stackoverflowerror                                                                                                                                        Out of memory error

 

 

1) Checked Exception

IOException, SQLException etc

 

2) Unchecked Exception

ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc

 

3) Error

OutOfMemoryError, VirtualMachineError, AssertionError etc.

 

Checked vs UnChecked Exception

Checked exceptions are subclass’s of Exception excluding RuntimeException and its subclasses

Unchecked exceptions are RuntimeException and any of its subclasses.

 

Checked Exceptions force programmers to deal with the exception that may be thrown.

A compiler doesn’t force the programmers to either catch the unchecked exception or declare it in a throws clause.

Programmers may not even know that the exception could be thrown

 

When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action,or pass the exception on to its caller.

 

Runtime exceptions do not need to be.

 

Checked exceptions must be caught at compile time.

 

Unchecked exceptions must be caught at run time.

 

Example

IO exception.

Example

ArrayIndexOutOfBounds Exception.

 

 

What are the In built Exceptions in Java?

ArithmeticException

ArrayIndexOutOfBoundsException

ClassNotFoundException

FileNotFoundException

IOException

InterruptedException

NoSuchFieldException

NoSuchMethodException

NullPointerException

NumberFormatException

RuntimeException

StringIndexOutOfBoundsException

 

What is Exception Handling?

A mechanism to handle the runtime error.

Handling exception means transferring the execution of the program to an appropriate handler when an exception occurs

Now we know that exception can occur in Java program at any time(or Any Location). So we need to know how to handle these exceptions.  Handling exception is a required attribute in developing a robust application. Handling Exception means transferring execution of the program to appropriate handler when an exception occurs. We can handle the exception by using try-catch block.

 

try: try is used to define the block of code where an exception can occur.

 

catch: catch is used to match a specific type of exception. There could be more than one catch clause for one try block.

 

finally: finally determine a block of code which will always execute after the try block. Even in the case of Exception.

 

try {

                                                throw new IOException();

                                } catch (IOException e) {

                                                // Handle only IO Exception

                                                // This block will get executed only in case of IOException

                                }catch (Exception e) {

                                                // Handle only all other type of exception

                                                // This block will get executed in case of all exception except IOException

                                }finally{

                                                System.out.println("This block will get executed no matter exception occur or not");

                                }

 

Error vs Exception

Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.

 

 

Exception Propagation

It is not required to handle all exception thrown by try block in the catch block (As it is not required block). In case catch block doesn’t handle the exception thrown by try block, it will be propagated to the method where this method was called from. In case the previous method which called this method also doesn’t handle it, the exception will be propagated to the last method in method stack, and it will keep propagating in the same way unless some method handle it. In case none of the methods handle it in the call stack, the exception will reach to bottom and JVM will handle it.

 

Java Keywords

TRY CATCH FINALLY THROW THROWS

 

TRY & CATCH

Java try block is used to enclose the code that might throw an exception. It must be used within the method.

If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.

Java try block must be followed by either catch or finally block.

 

package selenium;

public class Expectionhandling {

                public static void main(String[] args) {

                                // TODO Auto-generated method stub

                                int a;

                                a=100/0;

                                System.out.println(a);

                                System.out.println("Test");

                }

}

Output

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

                at selenium.Expectionhandling.main(Expectionhandling.java:8)

               

How to handle the exception using try catch block?

 

public static void main(String args[]){ 

   try{ 

      //code that may raise exception 

      int a=100/0; 

   }catch(ArithmeticException e){System.out.println(e);} 

   //rest code of the program  

   System.out.println("rest of the code..."); 

  } 

} 

Output:

java.lang.ArithmeticException: / by zero

rest of the code...

 

Multiple catch

A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block

At a time only one exception occurs and at a time only one catch block is executed.

All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.

 

public static void main(String[] args) { 

         

           try{   

                

               }   

               catch(Exception e) 

                  { 

                   

                  }   

               catch(Exception e) 

                  { 

                    

                  }   

               catch(Exception e) 

                  { 

                    

                  }            

               System.out.println("rest of the code");   

    } 

 

Eg:

 try{    

                int a[]=new int[5];    

                a[5]=30/0;    

               }    

               catch(ArithmeticException e)  

                  {  

                   System.out.println("Arithmetic Exception occurs");  

                  }    

               catch(ArrayIndexOutOfBoundsException e)  

                  {  

                   System.out.println("ArrayIndexOutOfBounds Exception occurs");  

                  }    

               catch(Exception e)  

                  {  

                   System.out.println("Parent Exception occurs");  

                  }             

               System.out.println("rest of the code");    

    }  

 

Nested Try

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error,

class classname{ 

 public static void main(String args[]){ 

  try{ 

    try{ 

     System.out.println("going to divide"); 

     int b =39/0; 

    }catch(ArithmeticException e){System.out.println(e);} 

  

    try{ 

    int a[]=new int[5]; 

    a[5]=4; 

    }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);} 

    

    System.out.println("other statement); 

  }catch(Exception e){System.out.println("handeled");} 

 

  System.out.println("normal flow.."); 

 } 

} 

               

Java finally block

To execute important code such as closing connection, stream etc.

always executed whether exception is handled or not.

follows try or catch block

It is used to put "cleanup" code such as closing a file, closing connection etc

 

3 sample cases to watch out the printing order when it handles the exception and also when it doesn’t,

 

1.finally example where exception doesn't occur

 

  public static void main(String args[]){ 

  try{ 

   int data=25/5; 

   System.out.println(data);  

  } 

  catch(NullPointerException e){System.out.println(e);} 

  finally{System.out.println("finally block is always executed");} 

  System.out.println("rest of the code..."); 

  } 

Output:5

       finally block is always executed

       rest of the code...

 

2.finally example where exception occurs and not handled.

try{ 

                     int data=25/0; 

                     System.out.println(data); 

                    } 

                   

            catch(NullPointerException e){System.out.println(e);} 

           

            finally{System.out.println("finally block is always executed");} 

           

            System.out.println("rest of the code..."); 

                    }

Output:
finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero

 

3.finally example where exception occurs and handled.

try{ 

                     int data=25/0; 

                     System.out.println(data); 

                    } 

                   

            catch(ArithmeticException e){System.out.println("Its an Arithmetic error");} 

           

            finally{System.out.println("finally block is always executed");} 

           

            System.out.println("rest of the code..."); 

                    }

Output:

Its an Arithmetic error

finally block is always executed

rest of the code...

 

THROW

 

The Java throw keyword is used to explicitly throw an exception.

Useful to throw the customized error messages. Much useful for the user defined exceptions.

public class TestThrow1{ 

   static void validate(int age){ 

     if(age<18) 

      throw new ArithmeticException("not valid"); 

     else 

      System.out.println("welcome to vote"); 

   } 

   public static void main(String args[]){ 

      validate(13); 

      System.out.println("rest of the code..."); 

  } 

} 

 

THROWS

 

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.

 

return_type method_name() throws exception_class_name{ 

//method code 

} 

Eg:

void m()throws ArithmeticException{ 

throw new ArithmeticException("sorry error occured"); 

} 

 

THROW

THROWS

Java throw keyword is used to explicitly throw an exception

Java throws keyword is used to declare an exception

Checked exception cannot be propagated using throw only

Checked exception can be propagated with throws

Throw is used within the method

Throws is used with the method signature

 

You cannot throw multiple exceptions

You can declare multiple exceptions e.g. public void method()throws IOException,SQLException

 

 

User Defined Exceptions

 

If you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

 

class InvalidAgeException extends Exception{ 

 InvalidAgeException(String s){ 

  super(s); 

 } 

} 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

class CustomException{ 

 

   static void validate(int age)throws InvalidAgeException{ 

     if(age<18) 

      throw new InvalidAgeException("not valid"); 

     else 

      System.out.println("welcome to vote"); 

   } 

     public static void main(String args[]){ 

      try{ 

      validate(13); 

      }catch(Exception a){System.out.println("Exception occured: "+a);

} 

        System.out.println("rest of the code..."); 

  } 

} 

output:

Exception occured: InvalidAgeException: not valid

 

To Summarize:

 

The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone.

 

The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.

 

The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not.

 

The "throw" keyword is used to throw an exception

 

The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.

 

try {

                                                throw new IOException();

                                } catch (IOException e) {

                                                // Handle only IO Exception

                                                // This block will get executed only in case of IOException

                                }catch (Exception e) {

                                                // Handle only all other type of exception

                                                // This block will get executed in case of all exception except IOException

                                }finally{

                                                System.out.println("This block will get executed no matter exception occur or not");

                                }