Top Posts
Virtual Function in C++
Ceil and Floor functions in C++
Python Rock Paper Scissors Game
AKTU MCA 4 SEMESTER QUESTION PAPERS
Git & Github 2021 Cheat Sheet
Introduction to C Programming Language
Git & Github 2021 Cheat Sheet
10+ C Program to Print Patterns
LUCKNOW BCA 6 SEM QUESTION PAPERS
Currency Converter in Python
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
    • UNIVERSITY PAPERS
    • MNC TWEETS
    • THINKECO INITIATIVES
    • CONTACT US
  • WRITE +
  • ABOUT US
  • HIRE US
Java Tutorial

Exception Handling in Java

by anupmaurya February 17, 2022
written by anupmaurya 0 comment 711 views

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 works at 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
Deloitte Recruitment For Any Graduates as Learning Operations Associate Analyst

You may also like

JDBC Components

Threads in Java

Life Cycle of a Servlet (Servlet Life Cycle)

XAMPP Tomcat/Error starting Tomcat

HttpServlet

GenericServlet

Inheritance and Access Modifiers in Java

Servlet Interface

Servlet API

Web Terminology

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[])
  • 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

  • Virtual Function in C++

    May 19, 2022
  • Ceil and Floor functions in C++

    May 19, 2022
  • Python Rock Paper Scissors Game

    May 18, 2022

EDUCATIONAL

  • 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

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

  • 10 mostly asked questions related to WhatsApp

  • Top 8 Programming Languages That Will Rule in 2022

  • Google Cloud Platform

  • Best Online Code Editors For Web Developers

  • How to Write a Synopsis for Project Work

CHEATSHEET

  • Git and Github 2022 Cheat Sheet

  • ReactJs Cheatsheet

  • Linux Commands Cheat Sheet

  • C Programming language Cheatsheet

  • Scala Cheatsheet

  • MySQL Cheatsheet

  • Javascript Cheatsheet

PROJECTS

  • Python Rock Paper Scissors Game

  • Currency Converter in Python

  • Alarm clock GUI application with tkinter

  • Print emojis using python without any module

  • Country Date and Time using Python

  • Covid-19 Tracker Application Using Python

  • Python | GUI Calendar using Tkinter

  • Python: Shutdown Computer with Voice

  • Python GUI Calculator using Tkinter

  • Convert an Image to ASCII art using Python

  • Python YouTube Downloader with Pytube

  • Tic-Tac-Toe using Python

TUTORIALS

  • JAVA TUTORIAL
  • COMPUTER NETWORK
  • DBMS TUTORIAL
  • E-COMMERCE TUTORIAL
  • KNOWLEDGE MANAGEMENT
  • C++ PROGRAMMING
  • COMPUTER NETWORK SECURITY
  • AMAZON WEB SERVICES

TECH NEWS

  • PyScript: Python in the Browser

  • HalloApp is a secure alternative to WhatsApp, made by two early WhatsApp employees

  • 5+ Best Humanoid Robots In The World

  • Windows 11 Now Official, Brings Fresh UI, Centrally-Placed Start Menu

TERMS & POLICY

  • PRIVACY POLICY
  • TERMS AND CONDITIONS

COMPILERS

  • JAVA COMPILER
  • PYTHON COMPILER
  • JS COMPILER
  • C++ COMPILER
  • C COMPILER

JOBS AND INTERNSHIPS

  • TCS off-campus hiring 2022 for software engineers- 2019, 2020, & 2021 Batches

    February 27, 2022
  • Deloitte Recruitment For Any Graduates as Learning Operations Associate Analyst

    February 18, 2022
  • HP Recruitment For Tech Support Intern Position

    February 16, 2022
  • EY Hiring- PAS Global Immigration Advanced Analyst

    February 14, 2022
  • Amazon Recruitment Drive for Virtual Customer Support Associate Position

    February 12, 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
    • UNIVERSITY PAPERS
    • MNC TWEETS
    • THINKECO INITIATIVES
    • CONTACT US
  • WRITE +
  • ABOUT US
  • HIRE US