Top Posts
Intranet Application Case Studies
Electronic E-commerce and the Trade Cycle
Types of JDBC drivers
C++ Program to implements Constructor Overloading
C++ Program to implements Constructor
C++ Program to calculate the area using classes
C++ Class Program to Store and Display Employee...
Operator Overloading of Decrement — Operator
Postfix Increment ++ Operator Overloading
Top 8 Programming Languages That Will Rule in...
TECHARGE
  • HOME
  • BLOGS
  • TUTORIALS
    • ALL TUTORIALS
    • PROGRAMMING TUTORIALS
      • JAVA TUTORIALS
      • C++ TUTORIAL
      • C PROGRAMMING TUTORIALS
      • PYTHON TUTORIAL
      • KNOWLEDGE MANAGEMENT TUTORIALS
      • DATA STRUCTURE AND ALGORITHM TUTORIALS
      • PROGRAMMING EXAMPLES
        • CPP EXAMPLES
        • JAVA EXAMPLES
        • C++ GRAPHICS PROGRAM
    • PROJECTS
      • PYTHON PROJECTS
      • SWIFT PROJECT
    • PPROGRAMMING QUIZ
    • DBMS TUTORIALS
    • COMPUTER NETWORK TUTORIALS
    • COMPUTER NETWORK SECURITY TUTORIALS
    • E COMMERCE TUTORIALS 
    • AWS TUTORIAL
    • INTERNET OF THINGS
    • CHEATSHEET
  • MORE
    • JOBS AND INTERNSHIPS
    • INTERVIEW PREPARATION
    • TECH BOOK
    • TECH NEWS
    • INSTAGRAM GALLERY
    • UNIVERSITY PAPERS
    • MNC TWEETS
    • THINKECO INITIATIVES
    • WEB STORIES
    • CONTACT US
  • WRITE +
  • ABOUT US
Java Tutorial

Exception Handling in Java

by anupmaurya November 16, 2022
written by anupmaurya 0 comment
1.2K

what is Exception Handling?

When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. So, the mechanism used to handle runtime errors are called Exception Handling.

Java exception handling is managed via five keywords:

Keyword Description
try 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.
catch The “catch” block is used to handle the exception. It must be preceded by try block which means we can’t use the catch block alone. It can be followed by finally block later.
finally The “finally” block is used to execute the important code of the program. It is executed whether an exception is handled or not.
throw The “throw” keyword is used to throw an exception.
throws 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.

How do we handle Exception ?

  1. Exception handling is accomplished through the “try-catch” mechanism, or by “throws” clause in the method declaration.
  2. For any code that throws a checked exception, you can decide to handle the exception yourself, or pass the exception “up the chain” (to a parent class).
  3. To handle the exception, you write a “try-catch” block. To pass the exception “up the chain”, you declare a “throws” clause in your method or class declaration.
  4. If the method contains code that may cause a checked exception, you MUST handle the exception OR pass the exception to the parent class.

Try-catch Mechanism

  • Try block

The try block contains set of statements where an exception can 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 be followed by catch blocks or finally block or both.

  • Catch block

A catch block is where you handle the exceptions, this block must follow the try block. A single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.

try-catch example:

class Example{
    public static void main(String[] arg) {
        int x, y;
        try{
            x = 0;
            y = 34/x;
            System.out.println(y);
        } catch(ArithmeticException e) {
            System.out.println("Should not divide  number by zero");
        }
        System.out.println("Out of try-catch block in Java.");
    }
}

try with multiple catch blocks example:

class Example{
    public static void main(String[] arg) {
        try{
            int[] x = new int[7];
            x[0] = 34/0;
            System.out.println("First Print in Try Block");
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException");
        }
        System.out.println("Out of try-catch block in Java.");
    }
}
/************************ OUT PUT ************************/
Arithmetic Exception
Out of try-catch block in Java.
Process finished with exit code 0

  • Finally block

  1. You can attach a finally-clause to a try-catch block.
  2. The code inside the finally clause will always be executed, even if an exception is thrown from within the try or catch block.
  3. If your code has a return statement inside the try or catch block, the code inside the finally-block will get executed before returning from the method.

class Example{
    public static void main(String[] arg) {
        try{
            int num =12/0;
            System.out.println(num);
        } catch (ArithmeticException e) {
            System.out.println("Divide by zero error");
        } finally {
            System.out.println("This will Execute Finally");
        }
    }
}
/************************ OUT PUT ************************/
Divide by zero error
This will Execute Finally
Process finished with exit code 0

KEY POINTS

  • checked & unchecked exception are two type of Exception.
  • A checked exception is those exceptions which are the subtype of Exception class but excluding classes which extends Runtime exception.
  • A subtype of Error and Runtime Exceptions comes under unchecked Exception.
  • Finally block will always be invoked in all condition.
  • System.exit() is the only way when finally block will not get executed coz, in that case, JVM will shut down.
  • Custom Exception can also be created by extending Exception class.
  • Catch block should be ordered in the form of most specific to most general. Otherwise, the compiler will complain about unreachable code.

blockcatchexception.exception handlingthrowthrowstry
Share 3 FacebookTwitterLinkedinRedditWhatsappTelegramEmail
anupmaurya

Hey there, My name is Anup Maurya. I was born with love with programming and worked with TCS. One of best global (IT) services and consulting company as System Administrator . I also love graphics designing. It's my pleasure to have you here.

previous post
Exception in JAVA
next post
Abstraction and Encapsulation in Java

You may also like

Types of JDBC drivers

JDBC Architecture

Introduction to JDBC

Difference Between Applet and Servlet in Java

OOPs Concepts in Java

Constructors in Java

Extending Interface

Implementing Interfaces in Java

Interface in Java

Java AWT tutorial for beginners

Java Tutorial

  • Online Java Compiler
  • Introduction to Java Programming
  • How to Check version of Java installed in System ?
  • How to set Temporary and Permanent Paths in Java
  • Features of Java Programming
  • Java Comments
  • Java Keywords
  • Java Variables
  • Data Types in Java
  • Java Flow Control Statements
  • Bitwise operators in Java
  • Understanding public static void main(string args[]) in Java
  • Strings in Java
  • Final method in Java
  • Constructors in Java
  • Exception in JAVA
  • Exception Handling in Java
  • Arguments in Java with Examples
  • Difference between abstract class and interface
  • Interface in Java
  • Implementing Interfaces in Java
  • Java Event Handling
  • Extending Interface
  • Multithreading in Java
  • Threads in Java
  • Life cycle of a thread in Java
  • Java AWT tutorial for beginners
  • Introduction to JDBC
  • JDBC Components
  • Java Database Connections | JDBC Tutorial
  • DriverManager class
  • Connection interface
  • Statement interface
  • PreparedStatement interface
  • ResultSet interface
  • Java Database Connectivity with MySQL
  • Applet in Java
  • Difference Between Applet and Servlet in Java
  • Web Terminology
  • Servlets
  • Servlet Interface
  • Life Cycle of a Servlet (Servlet Life Cycle)
  • Servlet API
  • GenericServlet
  • HttpServlet
  • Steps to Create Servlet Application using tomcat server
  • Session Tracking Using Servlet
  • Introduction to JSP
  • The JSP API
  • The Lifecycle of a JSP
  • TAGS in JSP

Words from Readers

I Just go mad with this website I love the content and the way it you present I can easily understand anything from this Thank you everyone who are made this possible!

–Paras Singh Kaphalia

Recent Posts

  • Intranet Application Case Studies

    March 21, 2023
  • Electronic E-commerce and the Trade Cycle

    March 21, 2023
  • Types of JDBC drivers

    December 28, 2022

EDUCATIONAL

  • Top 8 Programming Languages That Will Rule in 2023

  • Difference between Google Cloud Platform, AWS and Azure

  • Google Apps You Should Be Using in 2022

  • Top Sites From Where You Can Learn

  • PyScript: Python in the Browser

  • Best Fake Email Generators (Free Temporary Email Address)

  • How to Find Out Who Owns a Domain Name

  • Mobile phone brands by country of origin

  • How to start a new YouTube Channel in 2022

  • Best way to use google search you won’t believe exist

CHEATSHEET

  • Git and Github 2022 Cheat Sheet

  • ReactJs Cheatsheet

  • Linux Commands Cheat Sheet

  • C Programming language Cheatsheet

  • Scala Cheatsheet

  • MySQL Cheatsheet

  • Javascript Cheatsheet

PROJECTS

  • Print emojis using python without any module

  • Country Date and Time using Python

  • Covid-19 Tracker Application Using Python

  • Python | GUI Calendar using Tkinter

  • Shutdown Computer with Voice Using Python

  • Python GUI Calculator using Tkinter

  • Convert an Image to ASCII art using Python

  • Python YouTube Downloader with Pytube

  • Tic-Tac-Toe using Python

  • Draw Indian Flag using Python

  • Drawing Pikachu with the Python turtle library

  • Word Dictionary using Tkinter

TECH NEWS

  • 5+ Best Humanoid Robots In The World

  • Reliance Jio launches streaming platform JioGamesWatch

  • Microsoft Teams down for thousands of users

  • Carbon: Google programming language as a C++ successor

JOBS AND INTERNSHIPS

  • Accenture Off Campus Hiring Drive | Associate Job | Program Project Management | 2019-2022 Batch| Apply Now

    September 1, 2022

@2019-21 - All Right Reserved. Designed and Developed by Techarge

TECHARGE
  • HOME
  • BLOGS
  • TUTORIALS
    • ALL TUTORIALS
    • PROGRAMMING TUTORIALS
      • JAVA TUTORIALS
      • C++ TUTORIAL
      • C PROGRAMMING TUTORIALS
      • PYTHON TUTORIAL
      • KNOWLEDGE MANAGEMENT TUTORIALS
      • DATA STRUCTURE AND ALGORITHM TUTORIALS
      • PROGRAMMING EXAMPLES
        • CPP EXAMPLES
        • JAVA EXAMPLES
        • C++ GRAPHICS PROGRAM
    • PROJECTS
      • PYTHON PROJECTS
      • SWIFT PROJECT
    • PPROGRAMMING QUIZ
    • DBMS TUTORIALS
    • COMPUTER NETWORK TUTORIALS
    • COMPUTER NETWORK SECURITY TUTORIALS
    • E COMMERCE TUTORIALS 
    • AWS TUTORIAL
    • INTERNET OF THINGS
    • CHEATSHEET
  • MORE
    • JOBS AND INTERNSHIPS
    • INTERVIEW PREPARATION
    • TECH BOOK
    • TECH NEWS
    • INSTAGRAM GALLERY
    • UNIVERSITY PAPERS
    • MNC TWEETS
    • THINKECO INITIATIVES
    • WEB STORIES
    • CONTACT US
  • WRITE +
  • ABOUT US