The document discusses Java exceptions. It defines exceptions as abnormal conditions that disrupt normal program flow. It describes different types of exceptions like checked exceptions, unchecked exceptions, and errors. It explains exception handling in Java using try, catch, finally, throw and throws keywords. It provides examples to demonstrate various exceptions like NullPointerException, ArrayIndexOutOfBoundsException, and rethrowing exceptions.
There are three main categories of exceptions in Java:
1. Checked exceptions must be handled by the programmer and cannot be ignored.
2. Unchecked exceptions occur during runtime due to programming errors. They can be ignored.
3. Errors are problems beyond the programmer's control, like stack overflows, and are also ignored.
Java uses five keywords to handle exceptions: try catches exceptions thrown within its block; catch handles caught exceptions; throw manually throws exceptions; throws declares exceptions a method may throw; and finally always executes regardless of exceptions. Programmers place exception-prone code in try blocks and use catch blocks to handle exceptions rationally.
The document discusses various aspects of exception handling in Java such as the different types of exceptions (checked, unchecked, errors), keywords used in exception handling (try, catch, finally, throw, throws), and common scenarios where exceptions may occur. It provides examples of using try-catch blocks to handle exceptions, throwing custom exceptions using throw, and declaring exceptions in method signatures using throws. Finally, it discusses some key differences between concepts like final, finally and finalize in Java.
VTU MCA 2022 JAVA Exceeption Handling.docxPoornima E.G.
The document discusses exception handling in Java. It defines exceptions as events that disrupt normal program flow and explains that exception handling allows the rest of the program to continue executing after an error occurs. It outlines the advantages of exception handling like improved reliability and flexibility. The document also covers exception hierarchies, checked vs unchecked exceptions, common exception types, and provides an example of exception handling code.
This document discusses exception handling in Java programming. It defines an exception as an unwanted event that interrupts normal program flow. Exceptions can be handled in Java to provide meaningful messages to users rather than system errors. The document covers checked and unchecked exceptions, try-catch blocks, multiple catch blocks, finally blocks, and throwing custom exceptions. It provides examples to illustrate exception handling concepts in Java.
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
The document discusses exception handling and multithreading in Java. It covers exception handling basics like checked and unchecked exceptions. It describes try, catch, throw, throws and finally keywords used in exception handling. It also discusses multiple catch clauses, nested try blocks and built-in exceptions. For multithreading, it defines processes and threads, and how to create multiple threads and handle thread synchronization and priorities in Java.
The document discusses exception handling in Java. It defines exceptions as abnormal conditions that disrupt normal program flow. Exception handling allows maintaining normal flow by catching and handling exceptions. There are two main exception types: checked exceptions which must be declared, and unchecked exceptions which do not. The try, catch, finally and throw keywords are used to define exception handling blocks to catch exceptions and define exception throwing methods. Finally blocks ensure code is always executed even if exceptions occur.
The document discusses Java exceptions. It defines exceptions as abnormal conditions that disrupt normal program flow. It describes different types of exceptions like checked exceptions, unchecked exceptions, and errors. It explains exception handling in Java using try, catch, finally, throw and throws keywords. It provides examples to demonstrate various exceptions like NullPointerException, ArrayIndexOutOfBoundsException, and rethrowing exceptions.
There are three main categories of exceptions in Java:
1. Checked exceptions must be handled by the programmer and cannot be ignored.
2. Unchecked exceptions occur during runtime due to programming errors. They can be ignored.
3. Errors are problems beyond the programmer's control, like stack overflows, and are also ignored.
Java uses five keywords to handle exceptions: try catches exceptions thrown within its block; catch handles caught exceptions; throw manually throws exceptions; throws declares exceptions a method may throw; and finally always executes regardless of exceptions. Programmers place exception-prone code in try blocks and use catch blocks to handle exceptions rationally.
The document discusses various aspects of exception handling in Java such as the different types of exceptions (checked, unchecked, errors), keywords used in exception handling (try, catch, finally, throw, throws), and common scenarios where exceptions may occur. It provides examples of using try-catch blocks to handle exceptions, throwing custom exceptions using throw, and declaring exceptions in method signatures using throws. Finally, it discusses some key differences between concepts like final, finally and finalize in Java.
VTU MCA 2022 JAVA Exceeption Handling.docxPoornima E.G.
The document discusses exception handling in Java. It defines exceptions as events that disrupt normal program flow and explains that exception handling allows the rest of the program to continue executing after an error occurs. It outlines the advantages of exception handling like improved reliability and flexibility. The document also covers exception hierarchies, checked vs unchecked exceptions, common exception types, and provides an example of exception handling code.
This document discusses exception handling in Java programming. It defines an exception as an unwanted event that interrupts normal program flow. Exceptions can be handled in Java to provide meaningful messages to users rather than system errors. The document covers checked and unchecked exceptions, try-catch blocks, multiple catch blocks, finally blocks, and throwing custom exceptions. It provides examples to illustrate exception handling concepts in Java.
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
The document discusses exception handling and multithreading in Java. It covers exception handling basics like checked and unchecked exceptions. It describes try, catch, throw, throws and finally keywords used in exception handling. It also discusses multiple catch clauses, nested try blocks and built-in exceptions. For multithreading, it defines processes and threads, and how to create multiple threads and handle thread synchronization and priorities in Java.
The document discusses exception handling in Java. It defines exceptions as abnormal conditions that disrupt normal program flow. Exception handling allows maintaining normal flow by catching and handling exceptions. There are two main exception types: checked exceptions which must be declared, and unchecked exceptions which do not. The try, catch, finally and throw keywords are used to define exception handling blocks to catch exceptions and define exception throwing methods. Finally blocks ensure code is always executed even if exceptions occur.
The document discusses exception handling in Java. It defines exceptions as abnormal conditions that disrupt normal program flow. Exception handling allows the program to maintain normal flow when exceptions occur. There are two main types of exceptions: checked exceptions which must be declared, and unchecked exceptions which do not need to be declared. The try, catch, and finally keywords are used to handle exceptions, with try blocks enclosing code that might throw exceptions, catch blocks handling specific exceptions, and finally blocks containing cleanup code.
This document discusses exception handling in Java. It defines exceptions as abnormal conditions that disrupt normal program flow. Exception handling allows programs to gracefully handle runtime errors. The key aspects covered include the exception hierarchy, try-catch-finally syntax, checked and unchecked exceptions, and creating user-defined exceptions.
An exception is a problem that arises during the time of execution of program. An exception can occur for many different reasons, including the following.
A user has enter invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communicatons,or the JVM has run out of memory.
Some of these exception are caused by user error, others by programmer error, and others by physical resources, that have failed in some manner.
unit 4 msbte syallbus for sem 4 2024-2025AKSHAYBHABAD5
The Intel 8086 microprocessor, designed by Intel in the late 1970s, is an 8-bit/16-bit microprocessor and the first member of the x86 family of microprocessors1. Here’s a brief overview of its internal architecture:
Complex Instruction Set Computer (CISC) Architecture: The 8086 microprocessor is based on a CISC architecture, which supports a wide range of instructions, many of which can perform multiple operations in a single instruction1.
Bus Interface Unit (BIU): The BIU is responsible for fetching instructions from memory and decoding them, while also managing data transfer between the microprocessor and memory or I/O devices1.
Execution Unit (EU): The EU executes the instructions1.
Memory Segmentation: The 8086 microprocessor has a segmented memory architecture, which means that memory is divided into segments that are addressed using both a segment register and an offset1.
Registers: The 8086 microprocessor has a rich set of registers, including general-purpose registers, segment registers, and special registers
The document provides information about exceptions and applets in Java. It discusses exception handling in Java, including checked and unchecked exceptions. It also covers the try, catch, throw and throws keywords used in exception handling. Additionally, it describes applets in Java, including how applets extend the Applet class, their lifecycle through init(), start(), stop() and destroy() methods, and how to invoke an applet through HTML tags.
Exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object oriented way to handle exception scenarios, known as Java Exception Handling.
Ch-1_5.pdf this is java tutorials for allHayomeTakele
The document discusses exception handling in Java. It defines exceptions as abnormal conditions that occur during runtime and disrupt normal program flow. It describes different types of exceptions like checked, unchecked, and errors. It explains concepts like exception handling syntax using try, catch, finally blocks to maintain program flow. It provides examples to demonstrate exception handling and resolving exceptions in catch blocks.
1. Exception handling separates error-handling code from normal code to make programs more readable and robust.
2. There are two main types of exceptions: checked exceptions which must be caught or declared, and unchecked exceptions which do not typically need to be caught.
3. The try-catch block is used to catch exceptions, where code after the try is run inside a try block and any matching exceptions are caught and handled in corresponding catch blocks.
This document discusses Java exception handling. It begins by defining exceptions as abnormal or unexpected events that occur during runtime. It then describes the class hierarchy for exceptions, with Throwable at the top and Exception and Error as subclasses. When an exception occurs, an exception object is created and passed to the runtime system. The runtime system searches the call stack for an exception handler using try-catch blocks. The try-catch blocks allow code to execute normally or provide handling for exceptions. There are also finally blocks, throw clauses, and throws clauses for exception handling. Exceptions can be either unchecked, which do not require exception handling code, or checked, which do require exception handling code to comply with the "catch or specify" requirement.
Exception is an error event that can occur during program execution and disrupt normal flow. Java provides try, catch, throw, throws and finally keywords to handle exceptions. try is used to mark code that might throw exceptions, catch handles exceptions, throw throws exceptions, throws declares exceptions a method can throw, and finally always executes. There are two types of exceptions - checked exceptions which must be caught or declared thrown, and runtime exceptions which do not require handling. The Throwable class is at the top of the exception hierarchy, with Error and Exception subclasses.
Exception is an error event that can occur during program execution and disrupt normal flow. Java provides try, catch, throw, throws and finally keywords to handle exceptions. try is used to mark code that might throw exceptions, catch handles exceptions, throw throws exceptions, throws declares exceptions a method can throw, and finally always executes. There are two categories of exceptions - checked exceptions which must be caught or declared thrown, and runtime exceptions which do not require handling.
Exceptions are abnormal conditions that interrupt normal program execution. There are two main types: errors thrown by the runtime system that cannot be recovered from, and exceptions that can be handled through try/catch blocks. Exceptions are arranged in a hierarchy with Throwable at the top and checked and unchecked exceptions extending Exception or RuntimeException respectively. Checked exceptions must be handled, while unchecked exceptions do not need to be but can be. Exception handling uses try/catch/finally blocks, with catch providing recovery code and finally running regardless of exceptions. Custom exceptions can also be created by extending the Exception class. Exceptions propagate up the call stack to find matching handler code.
Exception handling in Java provides a robust way to handle errors and exceptions that occur during program execution. The try-catch block allows code to be wrapped in a try block to protect it, while catch blocks handle any exceptions. Multiple catch blocks can be used to handle different exception types. The throw keyword is used to manually throw an exception, while throws is used to indicate unhandled exceptions in a method signature. Finally, the finally block is used for cleanup and always executes regardless of exceptions.
An exception occurs when the normal flow of a program is disrupted, such as dividing by zero or accessing an out-of-bounds array element. Exceptions are handled using try-catch blocks to catch specific exceptions or finally blocks to clean up resources. Methods can throw exceptions using the throw statement or specify thrown exceptions in the method declaration using throws. Programmers can also create custom exception classes by extending the Exception class.
The document discusses exception handling in Java programs. It defines exceptions as errors that occur during runtime, explains why exceptions occur, and covers checked and unchecked exception types. It also describes the exception handling mechanism in Java using try, catch, and finally keywords, and lists some example exception classes. The advantages of exception handling are maintaining normal program flow, flexibility in error handling, and separating error code from regular code.
The document discusses exception handling in Java. It provides definitions of exceptions as abnormal conditions or events that disrupt normal program flow. Exception handling allows the normal flow to be maintained by catching and handling exceptions. There are two main types of exceptions - checked exceptions which are compiler-checked, and unchecked exceptions which occur at runtime. The try-catch block is used to catch exceptions, while finally blocks ensure cleanup code is always executed.
This document discusses exception handling in Java. It defines what exceptions are, why they occur, and what exception handling is. It describes the advantages of exception handling and differences between exceptions and errors. It covers the exception class hierarchy and exception handling keywords like try, catch, finally, throw, and throws. It provides examples of common exception types and an example Java code demonstrating exception handling.
Resumes, Cover Letters, and Applying OnlineBruce Bennett
This webinar showcases resume styles and the elements that go into building your resume. Every job application requires unique skills, and this session will show you how to improve your resume to match the jobs to which you are applying. Additionally, we will discuss cover letters and learn about ideas to include. Every job application requires unique skills so learn ways to give you the best chance of success when applying for a new position. Learn how to take advantage of all the features when uploading a job application to a company’s applicant tracking system.
More Related Content
Similar to Exception Handling Multithreading: Fundamental of Exception; Exception types; Using try and catch; Multiple Catch.
The document discusses exception handling in Java. It defines exceptions as abnormal conditions that disrupt normal program flow. Exception handling allows the program to maintain normal flow when exceptions occur. There are two main types of exceptions: checked exceptions which must be declared, and unchecked exceptions which do not need to be declared. The try, catch, and finally keywords are used to handle exceptions, with try blocks enclosing code that might throw exceptions, catch blocks handling specific exceptions, and finally blocks containing cleanup code.
This document discusses exception handling in Java. It defines exceptions as abnormal conditions that disrupt normal program flow. Exception handling allows programs to gracefully handle runtime errors. The key aspects covered include the exception hierarchy, try-catch-finally syntax, checked and unchecked exceptions, and creating user-defined exceptions.
An exception is a problem that arises during the time of execution of program. An exception can occur for many different reasons, including the following.
A user has enter invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communicatons,or the JVM has run out of memory.
Some of these exception are caused by user error, others by programmer error, and others by physical resources, that have failed in some manner.
unit 4 msbte syallbus for sem 4 2024-2025AKSHAYBHABAD5
The Intel 8086 microprocessor, designed by Intel in the late 1970s, is an 8-bit/16-bit microprocessor and the first member of the x86 family of microprocessors1. Here’s a brief overview of its internal architecture:
Complex Instruction Set Computer (CISC) Architecture: The 8086 microprocessor is based on a CISC architecture, which supports a wide range of instructions, many of which can perform multiple operations in a single instruction1.
Bus Interface Unit (BIU): The BIU is responsible for fetching instructions from memory and decoding them, while also managing data transfer between the microprocessor and memory or I/O devices1.
Execution Unit (EU): The EU executes the instructions1.
Memory Segmentation: The 8086 microprocessor has a segmented memory architecture, which means that memory is divided into segments that are addressed using both a segment register and an offset1.
Registers: The 8086 microprocessor has a rich set of registers, including general-purpose registers, segment registers, and special registers
The document provides information about exceptions and applets in Java. It discusses exception handling in Java, including checked and unchecked exceptions. It also covers the try, catch, throw and throws keywords used in exception handling. Additionally, it describes applets in Java, including how applets extend the Applet class, their lifecycle through init(), start(), stop() and destroy() methods, and how to invoke an applet through HTML tags.
Exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object oriented way to handle exception scenarios, known as Java Exception Handling.
Ch-1_5.pdf this is java tutorials for allHayomeTakele
The document discusses exception handling in Java. It defines exceptions as abnormal conditions that occur during runtime and disrupt normal program flow. It describes different types of exceptions like checked, unchecked, and errors. It explains concepts like exception handling syntax using try, catch, finally blocks to maintain program flow. It provides examples to demonstrate exception handling and resolving exceptions in catch blocks.
1. Exception handling separates error-handling code from normal code to make programs more readable and robust.
2. There are two main types of exceptions: checked exceptions which must be caught or declared, and unchecked exceptions which do not typically need to be caught.
3. The try-catch block is used to catch exceptions, where code after the try is run inside a try block and any matching exceptions are caught and handled in corresponding catch blocks.
This document discusses Java exception handling. It begins by defining exceptions as abnormal or unexpected events that occur during runtime. It then describes the class hierarchy for exceptions, with Throwable at the top and Exception and Error as subclasses. When an exception occurs, an exception object is created and passed to the runtime system. The runtime system searches the call stack for an exception handler using try-catch blocks. The try-catch blocks allow code to execute normally or provide handling for exceptions. There are also finally blocks, throw clauses, and throws clauses for exception handling. Exceptions can be either unchecked, which do not require exception handling code, or checked, which do require exception handling code to comply with the "catch or specify" requirement.
Exception is an error event that can occur during program execution and disrupt normal flow. Java provides try, catch, throw, throws and finally keywords to handle exceptions. try is used to mark code that might throw exceptions, catch handles exceptions, throw throws exceptions, throws declares exceptions a method can throw, and finally always executes. There are two types of exceptions - checked exceptions which must be caught or declared thrown, and runtime exceptions which do not require handling. The Throwable class is at the top of the exception hierarchy, with Error and Exception subclasses.
Exception is an error event that can occur during program execution and disrupt normal flow. Java provides try, catch, throw, throws and finally keywords to handle exceptions. try is used to mark code that might throw exceptions, catch handles exceptions, throw throws exceptions, throws declares exceptions a method can throw, and finally always executes. There are two categories of exceptions - checked exceptions which must be caught or declared thrown, and runtime exceptions which do not require handling.
Exceptions are abnormal conditions that interrupt normal program execution. There are two main types: errors thrown by the runtime system that cannot be recovered from, and exceptions that can be handled through try/catch blocks. Exceptions are arranged in a hierarchy with Throwable at the top and checked and unchecked exceptions extending Exception or RuntimeException respectively. Checked exceptions must be handled, while unchecked exceptions do not need to be but can be. Exception handling uses try/catch/finally blocks, with catch providing recovery code and finally running regardless of exceptions. Custom exceptions can also be created by extending the Exception class. Exceptions propagate up the call stack to find matching handler code.
Exception handling in Java provides a robust way to handle errors and exceptions that occur during program execution. The try-catch block allows code to be wrapped in a try block to protect it, while catch blocks handle any exceptions. Multiple catch blocks can be used to handle different exception types. The throw keyword is used to manually throw an exception, while throws is used to indicate unhandled exceptions in a method signature. Finally, the finally block is used for cleanup and always executes regardless of exceptions.
An exception occurs when the normal flow of a program is disrupted, such as dividing by zero or accessing an out-of-bounds array element. Exceptions are handled using try-catch blocks to catch specific exceptions or finally blocks to clean up resources. Methods can throw exceptions using the throw statement or specify thrown exceptions in the method declaration using throws. Programmers can also create custom exception classes by extending the Exception class.
The document discusses exception handling in Java programs. It defines exceptions as errors that occur during runtime, explains why exceptions occur, and covers checked and unchecked exception types. It also describes the exception handling mechanism in Java using try, catch, and finally keywords, and lists some example exception classes. The advantages of exception handling are maintaining normal program flow, flexibility in error handling, and separating error code from regular code.
The document discusses exception handling in Java. It provides definitions of exceptions as abnormal conditions or events that disrupt normal program flow. Exception handling allows the normal flow to be maintained by catching and handling exceptions. There are two main types of exceptions - checked exceptions which are compiler-checked, and unchecked exceptions which occur at runtime. The try-catch block is used to catch exceptions, while finally blocks ensure cleanup code is always executed.
This document discusses exception handling in Java. It defines what exceptions are, why they occur, and what exception handling is. It describes the advantages of exception handling and differences between exceptions and errors. It covers the exception class hierarchy and exception handling keywords like try, catch, finally, throw, and throws. It provides examples of common exception types and an example Java code demonstrating exception handling.
Similar to Exception Handling Multithreading: Fundamental of Exception; Exception types; Using try and catch; Multiple Catch. (20)
Resumes, Cover Letters, and Applying OnlineBruce Bennett
This webinar showcases resume styles and the elements that go into building your resume. Every job application requires unique skills, and this session will show you how to improve your resume to match the jobs to which you are applying. Additionally, we will discuss cover letters and learn about ideas to include. Every job application requires unique skills so learn ways to give you the best chance of success when applying for a new position. Learn how to take advantage of all the features when uploading a job application to a company’s applicant tracking system.
Leadership Ambassador club Adventist modulekakomaeric00
Aims to equip people who aspire to become leaders with good qualities,and with Christian values and morals as per Biblical teachings.The you who aspire to be leaders should first read and understand what the ambassador module for leadership says about leadership and marry that to what the bible says.Christians sh
5 Common Mistakes to Avoid During the Job Application Process.pdfAlliance Jobs
The journey toward landing your dream job can be both exhilarating and nerve-wracking. As you navigate through the intricate web of job applications, interviews, and follow-ups, it’s crucial to steer clear of common pitfalls that could hinder your chances. Let’s delve into some of the most frequent mistakes applicants make during the job application process and explore how you can sidestep them. Plus, we’ll highlight how Alliance Job Search can enhance your local job hunt.
IT Career Hacks Navigate the Tech Jungle with a RoadmapBase Camp
Feeling overwhelmed by IT options? This presentation unlocks your personalized roadmap! Learn key skills, explore career paths & build your IT dream job strategy. Visit now & navigate the tech world with confidence! Visit https://www.basecamp.com.sg for more details.
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...dsnow9802
Jill Pizzola's tenure as Senior Talent Acquisition Partner at THOMSON REUTERS in Marlton, New Jersey, from 2018 to 2023, was marked by innovation and excellence.
Learnings from Successful Jobs SearchersBruce Bennett
Are you interested to know what actions help in a job search? This webinar is the summary of several individuals who discussed their job search journey for others to follow. You will learn there are common actions that helped them succeed in their quest for gainful employment.
Joyce M Sullivan, Founder & CEO of SocMediaFin, Inc. shares her "Five Questions - The Story of You", "Reflections - What Matters to You?" and "The Three Circle Exercise" to guide those evaluating what their next move may be in their careers.
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?NWEXAM
Begin Your Preparation Here: https://bit.ly/3VfYStG — Access comprehensive details on the FCP_FAC_AD-6.5 exam guide and excel in the Fortinet Certified Professional - Network Security certification. Gather all essential information including tutorials, practice tests, books, study materials, exam questions, and the syllabus. Solidify your knowledge of Fortinet FCP_FAC_AD-6.5 certification. Discover everything about the FCP_FAC_AD-6.5 exam, including the number of questions, passing percentage, and the time allotted to complete the test.
Job Finding Apps Everything You Need to Know in 2024SnapJob
SnapJob is revolutionizing the way people connect with work opportunities and find talented professionals for their projects. Find your dream job with ease using the best job finding apps. Discover top-rated apps that connect you with employers, provide personalized job recommendations, and streamline the application process. Explore features, ratings, and reviews to find the app that suits your needs and helps you land your next opportunity.
A Guide to a Winning Interview June 2024Bruce Bennett
This webinar is an in-depth review of the interview process. Preparation is a key element to acing an interview. Learn the best approaches from the initial phone screen to the face-to-face meeting with the hiring manager. You will hear great answers to several standard questions, including the dreaded “Tell Me About Yourself”.
Exception Handling Multithreading: Fundamental of Exception; Exception types; Using try and catch; Multiple Catch.
1. Unit - III
Exception Handling and Multithreading
What is Exception in Java?
Exceptions are events that occur during the execution of programs that disrupt the
normal flow of instructions (e.g. divide by zero, array access out of bound, etc.).
Exception is an object which is thrown at runtime.
Exception objects can be thrown and caught.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException,
IOException,
SQLException,
RemoteException, etc.
Advantage of Exception Handling
The advantage of exception handling is to maintain the normal flow of the
application.
An exception normally disrupts the normal flow of the application; that is why we
need to handle exceptions.
2. Example:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at
statement 5;
The rest of the code will not be executed, i.e., statements 6 to 10 will not be
executed.
However, when we perform exception handling, the rest of the statements will be
executed. That is why we use exception handling in Java.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception.
The hierarchy inherited by two subclasses:
Exception and
Error
3. Exceptions are used to indicate many different types of error conditions.
JVM Errors:
OutOfMemoryError
StackOverflowError
LinkageError
System errors:
FileNotFoundException
IOException
4. SocketTimeoutException
Programming errors:
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries.
Java also allows users to define their own exceptions.
Exceptions can be categorized in two ways:
1. Built-in Exceptions
Checked Exception
Unchecked Exception
2. User-Defined Exceptions
1. Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries.
5. These exceptions are suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are called compile-time exceptions
because these exceptions are checked at compile-time by the compiler.
Unchecked Exceptions: The compiler will not check these exceptions at compile
time. In simple words, if a program throws an unchecked exception, and even if we
didn’t handle or declare it, the program would not give a compilation error.
2. User-Defined Exceptions:
Users can also create exceptions, which are called ‘user-defined Exceptions’.
Advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are
as follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0; //ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.
6. String s=null;
System.out.println(s.length()); //NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into
NumberFormatException.
Suppose we have a string variable that has characters; converting this variable into
digit will cause NumberFormatException.
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.
There may be other reasons to occur ArrayIndexOutOfBoundsException.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
7. Java Exception Keywords
Java provides five keywords that are used to handle the exception.
Keyword Description
Try The "try" keyword is used to specify a block where we
should place an exception code.
It means we can't use try block alone.
The try block must be followed by either catch or finally.
Catch 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.
Finally The "finally" block is used to execute the necessary 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 specifies that there may occur an exception in the method.
It doesn't throw an exception.
It is always used with method signature.
8. Java try and catch
The try statement allows you to define a block of code to be tested for errors while
it is being executed.
The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
Java try block:
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 in the try block, the rest of the
block code will not execute.
So, it is recommended not to keep the code in try block that will not throw an
exception.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch:
try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
}
Syntax of try-finally block:
Try
{
//code that may throw an exception
}
Finally
{
}
9. Java catch block
Java catch block is used to handle the Exception by declaring the type of exception
within the parameter.
The declared exception must be the parent class exception ( i.e., Exception)
The catch block must be used after the try block only.
You can use multiple catch block with a single try block.
Internal Working of Java try-catch block:
The JVM firstly checks whether the exception is handled or not.
If exception is not handled, JVM provides a default exception handler that performs
the following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
10. But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
Example1: Problem without exception handling
if we don't use a try-catch block.
public class TryCatchExample1
{
public static void main(String[] args)
{
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Example 2: Solution by exception handling
Using java try-catch block.
public class TryCatchExample2
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
11. }
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 3: In this example, we also kept the code in a try block that will not throw
an exception.
public class TryCatchExample3 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will
not execute.
12. Example 4: Here, we handle the exception using the parent class exception.
public class TryCatchExample4 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5: to print a custom message on exception.
public class TryCatchExample5 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
13. {
// displaying the custom message
System.out.println("Can't divided by zero");
}
}
}
Output: Can't divided by zero
Example 6: to resolve the exception in a catch block.
public class TryCatchExample6 {
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}
Output:
25
14. Java Multi-catch block:
A try block can be followed by one or more catch blocks.
Each catch block must contain a different exception handler.
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.
15. Example: java multi-catch block.
public class MultipleCatchBlock1 {
public static void main(String[] args) {
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");
}
}
OUTPUT
Arithmetic Exception occurs
rest of the code
Java Nested try block:
In Java, using a try block inside another try block is permitted. It is called as nested
try block.
For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).
17. }
....
Example: a try block within another try block for two different exceptions.
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
18. }
System.out.println("normal flow..");
}
}
Output:
Java throw keyword
The Java throw keyword is used to throw an exception explicitly.
We can define our own set of conditions and throw an exception explicitly using
throw keyword.
For example, we can throw ArithmeticException if we divide a number by another
number.
Here, we just need to set the condition and throw exception using throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
throw new exception_class("error message");
Example of throw IOException.
throw new IOException("sorry device error");
Java throw keyword Example
Example 1: Throwing Unchecked Exception
In this example, we have created a method named validate() that accepts an integer
as a parameter.
19. If the age is less than 18, we are throwing the ArithmeticException otherwise print a
message welcome to vote.
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Example 2: Throwing Checked Exception
Every subclass of Error and RuntimeException is an unchecked exception in java. A
checked exception is everything else under the Throwable class.
import java.io.*;
public class TestThrow2 {
20. //function to check if person is eligible to vote or not
public static void method() throws FileNotFoundException {
FileReader file = new FileReader("C:UsersAnuratiDesktopabc.txt");
BufferedReader fileInput = new BufferedReader(file);
throw new FileNotFoundException();
}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}
Output:
21. Example 3: Throwing User-defined Exception
exception is everything else under the Throwable class.
TestThrow3.java
// class represents user-defined exception
class UserDefinedException extends Exception
{
public UserDefinedException(String str)
{
// Calling constructor of parent Exception
super(str);
}
}
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude)
{
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
}
}
}
Output:
22. Java finally block
Java finally block is a block used to execute important code such as closing the
connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.
The finally block follows the try-catch block.
23. Example:
Case 1: When an exception does not occur
Java program does not throw any exception, and the finally block is executed after
the try block.
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
OUTPUT
Case 2: When an exception occur but not handled by the catch block
Here, the code throws an exception however the catch block cannot handle it.
24. Despite this, the finally block is executed after the try block and then the program
terminates abnormally.
public class TestFinallyBlock1{
public static void main(String args[]){
try {
System.out.println("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
25. Lab Program7:Write a java program to implement Exception Handling
import java.io.*;
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail=a;
}
public String toString()
{
return "Minor with age less than 18 and you are only "+detail;
}
}
class ExceptionDemo
{
static void compute(int x)throws MyException
{
if(x<18)
throw new MyException(x);
else
System.out.println("You can voten");
}
public static void main(String arg[])
{
try
{
compute(20);
compute(15);
}
catch(MyException e)
{
System.out.println("My Exception caught "+e);
}
finally
{
System.out.println("nYou are an Indian");
} } }