Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Java Hello World
  • Java JVM, JRE and JDK
  • Java Variables and Literals
  • Java Data Types
  • Java Operators
  • Java Input and Output
  • Java Expressions & Blocks
  • Java Comment

Java Flow Control

  • Java if...else
  • Java switch Statement
  • Java for Loop
  • Java for-each Loop
  • Java while Loop
  • Java break Statement
  • Java continue Statement
  • Java Arrays
  • Multidimensional Array
  • Java Copy Array

Java OOP (I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructor
  • Java Strings
  • Java Access Modifiers
  • Java this keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP (II)

  • Java Inheritance
  • Java Method Overriding
  • Java super Keyword
  • Abstract Class & Method
  • Java Interfaces
  • Java Polymorphism
  • Java Encapsulation

Java OOP (III)

  • Nested & Inner Class
  • Java Static Class
  • Java Anonymous Class
  • Java Singleton
  • Java enum Class
  • Java enum Constructor
  • Java enum String
  • Java Reflection

Java Exception Handling

  • Java Exceptions

Java try...catch

Java throw and throws

Java catch Multiple Exceptions

Java try-with-resources

  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java List Interface
  • Java ArrayList
  • Java Vector
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue Interface
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet
  • Java EnumSet
  • Java LinkedhashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator
  • Java ListIterator
  • Java I/O Streams
  • Java InputStream
  • Java OutputStream
  • Java FileInputStream
  • Java FileOutputStream
  • Java ByteArrayInputStream
  • Java ByteArrayOutputStream
  • Java ObjectInputStream
  • Java ObjectOutputStream
  • Java BufferedInputStream
  • Java BufferedOutputStream
  • Java PrintStream

Java Reader/Writer

  • Java Reader
  • Java Writer
  • Java InputStreamReader
  • Java OutputStreamWriter
  • Java FileReader
  • Java FileWriter
  • Java BufferedReader
  • Java BufferedWriter
  • Java StringReader
  • Java StringWriter
  • Java PrintWriter

Additional Topics

  • Java Scanner Class
  • Java Type Casting
  • Java autoboxing and unboxing
  • Java Lambda Expression
  • Java Generics
  • Java File Class
  • Java Wrapper Class
  • Java Command Line Arguments

Java Tutorials

In the last tutorial, we learned about Java exceptions . We know that exceptions abnormally terminate the execution of a program.

This is why it is important to handle exceptions. Here's a list of different approaches to handle exceptions in Java.

  • try...catch block
  • finally block
  • throw and throws keyword

1. Java try...catch block

The try-catch block is used to handle exceptions in Java. Here's the syntax of try...catch block:

Here, we have placed the code that might generate an exception inside the try block. Every try block is followed by a catch block.

When an exception occurs, it is caught by the catch block. The catch block cannot be used without the try block.

Example: Exception handling using try...catch

In the example, we are trying to divide a number by 0 . Here, this code generates an exception.

To handle the exception, we have put the code, 5 / 0 inside the try block. Now when an exception occurs, the rest of the code inside the try block is skipped.

The catch block catches the exception and statements inside the catch block is executed.

If none of the statements in the try block generates an exception, the catch block is skipped.

2. Java finally block

In Java, the finally block is always executed no matter whether there is an exception or not.

The finally block is optional. And, for each try block, there can be only one finally block.

The basic syntax of finally block is:

If an exception occurs, the finally block is executed after the try...catch block. Otherwise, it is executed after the try block. For each try block, there can be only one finally block.

Example: Java Exception Handling using finally block

In the above example, we are dividing a number by 0 inside the try block. Here, this code generates an ArithmeticException .

The exception is caught by the catch block. And, then the finally block is executed.

Note : It is a good practice to use the finally block. It is because it can include important cleanup codes like,

  • code that might be accidentally skipped by return, continue or break
  • closing a file or connection

3. Java throw and throws keyword

The Java throw keyword is used to explicitly throw a single exception.

When we throw an exception, the flow of the program moves from the try block to the catch block.

Example: Exception handling using Java throw

In the above example, we are explicitly throwing the ArithmeticException using the throw keyword.

Similarly, the throws keyword is used to declare the type of exceptions that might occur within the method. It is used in the method declaration.

Example: Java throws keyword

When we run this program, if the file test.txt does not exist, FileInputStream throws a FileNotFoundException which extends the IOException class.

The findFile() method specifies that an IOException can be thrown. The main() method calls this method and handles the exception if it is thrown.

If a method does not handle exceptions, the type of exceptions that may occur within it must be specified in the throws clause.

To learn more, visit Java throw and throws .

Table of Contents

  • Introduction
  • Java try...catch block
  • Java finally block
  • Java throw and throws keyword

Sorry about that.

Related Tutorials

Java Tutorial

Exception Handling in Java: A Complete Guide with Best and Worst Practices

java exception handling assignment

Handling Exceptions in Java is one of the most basic and fundamental things a developer should know by heart. Sadly, this is often overlooked and the importance of exception handling is underestimated - it's as important as the rest of the code.

In this article, let's go through everything you need to know about exception handling in Java, as well as good and bad practices.

  • What is Exception Handling?

We are surrounded by exception handling in real-life on an everyday basis.

When ordering a product from an online shop - the product may not be available in stock or there might occur a failure in delivery. Such exceptional conditions can be countered by manufacturing another product or sending a new one after the delivery failed.

When building applications - they might run into all kinds of exceptional conditions. Thankfully, being proficient in exception handling, such conditions can be countered by altering the flow of code.

  • Why use Exception Handling?

When building applications, we're usually working in an ideal environment - the file system can provide us with all of the files we request, our Internet connection is stable and the JVM can always provide enough memory for our needs.

Sadly, in reality, the environment is far from ideal - the file cannot be found, the Internet connection breaks from time to time and the JVM can't provide enough memory and we're left with a daunting StackOverflowError .

If we fail to handle such conditions, the whole application will end up in ruins, and all other code becomes obsolete. Therefore, we must be able to write code that can adapt to such situations.

Imagine a company not being able to resolve a simple issue that arose after ordering a product - you don't want your application to work that way.

  • Exception Hierarchy

All of this just begs the question - what are these exceptions in the eyes of Java and the JVM?

Exceptions are, after all, simply Java objects that extend the Throwable interface:

When we talk about exceptional conditions, we are usually referring to one of the three:

  • Checked Exceptions
  • Unchecked Exceptions / Runtime Exceptions

Note : The terms "Runtime" and "Unchecked" are often used interchangeably and refer to the same kind of exceptions.

Checked Exceptions are the exceptions that we can typically foresee and plan ahead in our application. These are also exceptions that the Java Compiler requires us to either handle-or-declare when writing code.

The handle-or-declare rule refers to our responsibility to either declare that a method throws an exception up the call stack - without doing much to prevent it or handle the exception with our own code, which typically leads to the recovery of the program from the exceptional condition.

This is the reason why they're called checked exceptions . The compiler can detect them before runtime, and you're aware of their potential existence while writing code.

  • Unchecked Exceptions

Unchecked Exceptions are the exceptions that typically occur due to human, rather than an environmental error. These exceptions are not checked during compile-time, but at runtime, which is the reason they're also called Runtime Exceptions .

They can often be countered by implementing simple checks before a segment of code that could potentially be used in a way that forms a runtime exception, but more on that later on.

Errors are the most serious exceptional conditions that you can run into. They are often irrecoverable and there's no real way to handle them. The only thing we, as developers, can do is optimize the code in hopes that the errors never occur.

Errors can occur due to human and environmental errors. Creating an infinitely recurring method can lead to a StackOverflowError , or a memory leak can lead to an OutOfMemoryError .

  • How to Handle Exceptions
  • throw and throws

The easiest way to take care of a compiler error when dealing with a checked exception is to simply throw it.

We are required to mark our method signature with a throws clause. A method can add as many exceptions as needed in its throws clause, and can throw them later on in the code, but doesn't have to. This method doesn't require a return statement, even though it defines a return type. This is because it throws an exception by default, which ends the flow of the method abruptly. The return statement, therefore, would be unreachable and cause a compilation error.

Keep in mind that anyone who calls this method also needs to follow the handle-or-declare rule.

When throwing an exception, we can either throw a new exception, like in the preceding example, or a caught exception.

  • try-catch Blocks

A more common approach would be to use a try - catch block to catch and handle the arising exception:

In this example, we "marked" a risky segment of code by encasing it within a try block. This tells the compiler that we're aware of a potential exception and that we're intending to handle it if it arises.

This code tries to read the contents of the file, and if the file is not found, the FileNotFoundException is caught and re-thrown . More on this topic later.

Running this piece of code without a valid URL will result in a thrown exception:

Alternatively, we can try to recover from this condition instead of re-throwing:

Running this piece of code without a valid URL will result in:

  • finally Blocks

Introducing a new kind of block, the finally block executes regardless of what happens in the try block. Even if it ends abruptly by throwing an exception, the finally block will execute.

This was often used to close the resources that were opened in the try block since an arising exception would skip the code closing them:

However, this approach has been frowned upon after the release of Java 7, which introduced a better and cleaner way to close resources, and is currently seen as bad practice.

  • try-with-resources Statement

The previously complex and verbose block can be substituted with:

It's much cleaner and it's obviously simplified by including the declaration within the parentheses of the try block.

Additionally, you can include multiple resources in this block, one after another:

This way, you don't have to concern yourself with closing the resources yourself, as the try-with-resources block ensures that the resources will be closed upon the end of the statement.

  • Multiple catch Blocks

When the code we're writing can throw more than one exception, we can employ several catch blocks to handle them individually:

When the try block incurs an exception, the JVM checks whether the first caught exception is an appropriate one, and if not, goes on until it finds one.

Note : Catching a generic exception will catch all of its subclasses so it's not required to catch them separately.

Catching a FileNotFound exception isn't necessary in this example, because it extends from IOException , but if the need arises, we can catch it before the IOException :

This way, we can handle the more specific exception in a different manner than a more generic one.

Note : When catching multiple exceptions, the Java compiler requires us to place the more specific ones before the more general ones, otherwise they would be unreachable and would result in a compiler error.

  • Union catch Blocks

To reduce boilerplate code, Java 7 also introduced union catch blocks . They allow us to treat multiple exceptions in the same manner and handle their exceptions in a single block:

  • How to throw exceptions

Sometimes, we don't want to handle exceptions. In such cases, we should only concern ourselves with generating them when needed and allowing someone else, calling our method, to handle them appropriately.

  • Throwing a Checked Exception

When something goes wrong, like the number of users currently connecting to our service exceeding the maximum amount for the server to handle seamlessly, we want to throw an exception to indicate an exceptional situation:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This code will increase numberOfUsers until it exceeds the maximum recommended amount, after which it will throw an exception. Since this is a checked exception, we have to add the throws clause in the method signature.

To define an exception like this is as easy as writing the following:

  • Throwing an Unchecked Exception

Throwing runtime exceptions usually boils down to validation of input, since they most often occur due to faulty input - either in the form of an IllegalArgumentException , NumberFormatException , ArrayIndexOutOfBoundsException , or a NullPointerException :

Since we're throwing a runtime exception, there's no need to include it in the method signature, like in the example above, but it's often considered good practice to do so, at least for the sake of documentation.

Again, defining a custom runtime exception like this one is as easy as:

  • Re-throwing

Re-throwing an exception was mentioned before so here's a short section to clarify:

Re-throwing refers to the process of throwing an already caught exception, rather than throwing a new one.

Wrapping, on the other hand, refers to the process of wrapping an already caught exception, within another exception:

  • Re-throwing Throwable or _Exception*?

These top-level classes can be caught and re-thrown, but how to do so can vary:

In this case, the method is throwing a NumberFormatException which is a runtime exception. Because of this, we don't have to mark the method signature with either NumberFormatException or Throwable .

However, if we throw a checked exception within the method:

We now have to declare that the method is throwing a Throwable . Why this can be useful is a broad topic that is out of scope for this blog, but there are usages for this specific case.

  • Exception Inheritance

Subclasses that inherit a method can only throw fewer checked exceptions than their superclass:

With this definition, the following method will cause a compiler error:

  • Best and Worst Exception Handling Practices

With all that covered, you should be pretty familiar with how exceptions work and how to use them. Now, let's cover the best and worst practices when it comes to handling exceptions which we hopefully understand fully now.

  • Best Exception Handling Practices
  • Avoid Exceptional Conditions

Sometimes, by using simple checks, we can avoid an exception forming altogether:

Calling this method with a valid index would result in:

But calling this method with an index that's out of bounds would result in:

In any case, even though the index is too high, the offending line of code will not execute and no exception will arise.

  • Use try-with-resources

As already mentioned above, it's always better to use the newer, more concise and cleaner approach when working with resources.

  • Close resources in try-catch-finally

If you're not utilizing the previous advice for any reason, at least make sure to close the resources manually in the finally block.

I won't include a code example for this since both have already been provided, for brevity.

  • Worst Exception Handling Practices
  • Swallowing Exceptions

If your intention is to simply satisfy the compiler, you can easily do so by swallowing the exception :

Swallowing an exception refers to the act of catching an exception and not fixing the issue.

This way, the compiler is satisfied since the exception is caught, but all the relevant useful information that we could extract from the exception for debugging is lost, and we didn't do anything to recover from this exceptional condition.

Another very common practice is to simply print out the stack trace of the exception:

This approach forms an illusion of handling. Yes, while it is better than simply ignoring the exception, by printing out the relevant information, this doesn't handle the exceptional condition any more than ignoring it does.

  • Return in a finally Block

According to the JLS ( Java Language Specification ):

If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice.

So, in the terminology of the documentation, if the finally block completes normally, then the try statement completes abruptly for reason R.

If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).

In essence, by abruptly returning from a finally block, the JVM will drop the exception from the try block and all valuable data from it will be lost:

In this case, even though the try block throws a new IOException , we use return in the finally block, ending it abruptly. This causes the try block to end abruptly due to the return statement, and not the IOException , essentially dropping the exception in the process.

  • Throwing in a finally Block

Very similar to the previous example, using throw in a finally block will drop the exception from the try-catch block:

In this example, the MyException thrown inside the finally block will overshadow the exception thrown by the catch block and all valuable information will be dropped.

  • Simulating a goto statement

Critical thinking and creative ways to find a solution to a problem is a good trait, but some solutions, as creative as they are, are ineffective and redundant.

Java doesn't have a goto statement like some other languages but rather uses labels to jump around the code:

Yet still some people use exceptions to simulate them:

Using exceptions for this purpose is ineffective and slow. Exceptions are designed for exceptional code and should be used for exceptional code.

  • Logging and Throwing

When trying to debug a piece of code and finding out what's happening, don't both log and throw the exception:

Doing this is redundant and will simply result in a bunch of log messages which aren't really needed. The amount of text will reduce the visibility of the logs.

  • Catching Exception or Throwable
Why don't we simply catch Exception or Throwable, if it catches all subclasses?

Unless there's a good, specific reason to catch any of these two, it's generally not advised to do so.

Catching Exception will catch both checked and runtime exceptions. Runtime exceptions represent problems that are a direct result of a programming problem, and as such shouldn't be caught since it can't be reasonably expected to recover from them or handle them.

Catching Throwable will catch everything . This includes all errors, which aren't actually meant to be caught in any way.

In this article, we've covered exceptions and exception handling from the ground up. Afterwards, we've covered the best and worst exception handling practices in Java.

Hopefully you found this blog informative and educational, happy coding!

You might also like...

  • Java: Finding Duplicate Elements in a Stream
  • Spring Boot with Redis: HashOperations CRUD Functionality
  • Spring Cloud: Hystrix
  • Java Regular Expressions - How to Validate Emails

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.

In this article

Make clarity from data - quickly learn data visualization with python.

Learn the landscape of Data Visualization tools in Python - work with Seaborn , Plotly , and Bokeh , and excel in Matplotlib !

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013- 2024 Stack Abuse. All rights reserved.

[email protected]

about us

Java Exception Handling: Try, Catch, Finally Explained

Java Exception Handling: Try, Catch, Finally Explained

  • 13th Mar 2024

In the world of Java programming , unexpected events can disrupt the smooth execution of your code. These unforeseen circumstances, known as exceptions, can arise due to various reasons: user input errors, file access issues, network problems, or internal logic flaws. Left unhandled, exceptions can lead to program crashes, leaving users confused and frustrated.

Errors happen. Java's try-catch-finally structure helps manage them gracefully. The try block holds error-prone code, while catch blocks define actions for specific exceptions. Finally, the finally block executes code regardless of errors, often for cleanup tasks. This approach prevents crashes, maintains program flow, and protects data integrity, leading to more reliable and user-friendly software.

The try block serves as the foundation, where you place the code susceptible to exceptions. If an exception occurs during execution within the try block, control is transferred to the catch block(s) designed to handle that specific type of exception. Finally, the finally block, if present, guarantees execution regardless of how the try block exits (normally or due to an exception). Let's delve deeper into each component to understand their roles and functionalities in detail.

Struggling with Java exception handling in your assignments or homework? Master the try-catch-finally construct and conquer those errors! Dive into our comprehensive Java Assignment Help and Java Homework Help service and conquer your coding challenges!

The Try Block

The try block forms the core of Java's exception-handling mechanism. It serves as a designated zone where you place code segments that have the potential to throw exceptions during execution. These could be operations involving:

  • File access
  • Network communication
  • Any other scenario prone to unforeseen errors

Execution Flow within the Try Block:

  • Code within the try block executes normally as long as no exceptions are encountered.
  • The program proceeds sequentially, line by line, until it reaches the end of the try block or an exception disrupts the normal flow.

Importance of Encapsulating Exception-Prone Code:

Placing potentially error-prone code within the try block allows the program to anticipate and manage exceptions gracefully. By isolating these sections, you create a controlled environment with several benefits:

  • Anticipates exceptions: The try block flags potential trouble spots in your code.
  • Controlled response: You can define how the program reacts to exceptions within the try block.
  • Prevents program crashes: By handling exceptions, you avoid abrupt program termination due to errors.

For instance, imagine a code snippet reading data from a file. This operation could potentially throw an IOException if the file doesn't exist or is inaccessible:

try {   // Code that reads data from a file (potentially throws IOException) } catch (IOException e) {   // Code to handle the IOException (e.g., display error message) }

By using exception handling, you make your program more resilient. It can handle unexpected situations gracefully, preventing crashes and providing a better experience for the user. This allows your program to continue running smoothly even when file reading encounters problems.

Limitations of the Try Block:

It's important to note that the try block itself doesn't handle exceptions. Its primary role is to identify potentially risky code segments. However, it has one significant limitation: unchecked exceptions. These runtime errors, like NullPointerException or ArrayIndexOutOfBoundsException, bypass the try-catch mechanism entirely and can still lead to program termination if not handled elsewhere in your code.

The Catch Block

The catch block acts as the hero in Java's exception-handling drama. It's where you define how to handle exceptions that erupt within the corresponding try block. Here's how it all plays out:

The Role of the Catch Block:

Imagine an exception erupts during code execution within the try block. The program flow redirects to the first catch block that can handle the specific type of exception thrown. This catch block then contains the code responsible for dealing with the exception in a meaningful way.

Catching and Handling Exceptions:

  • Catching: A catch block is defined using the catch keyword followed by parentheses containing the exception type it can handle.
  • Handling: The code within the catch block addresses the exception. This might involve displaying an error message, logging the error for debugging purposes, attempting to recover from the error, or gracefully terminating the program.

Multiple Catch Blocks and Exception Hierarchies:

You can define multiple catch blocks after a single try block. The order of these catch blocks is crucial. Java scans them from top to bottom, looking for the first catch block that matches the type of exception thrown. Here are two common approaches:

  • Specific Exception Types: Define a separate catch block for each specific exception type you anticipate. This provides granular control over how different exceptions are handled.

try {   // Code that might throw exceptions } catch (IOException e) {   // Handle IOException } catch (NumberFormatException e) {   // Handle NumberFormatException }

  • Parent-Child Exception Hierarchies: Leverage Java's exception hierarchy. You can use a catch block that handles a parent exception type, effectively catching all its child exceptions as well.

try {   // Code that might throw exceptions } catch (Exception e) {   // Handle all Exception types (including subclasses like IOException) }

Exception Chaining with Throwable:

Java exceptions help handle errors. While the Throwable class lets you catch any type of exception, it's generally not recommended. This is because catching everything makes your code harder to understand. It's better to catch specific exceptions so you can provide targeted solutions and keep your code clean and clear.

Limitations of Catch Blocks:

While catch blocks are powerful, they have limitations:

  • Multiple Exceptions: Your code might face different errors. Use separate catch blocks for each specific exception you expect. But be mindful - too many can clutter things up! Aim for catching specific errors for cleaner code. Remember, the order of catch blocks matters - list the most specific exceptions first!
  • Rethrowing Exceptions: In programming, rethrowing an exception means catching it and then throwing it again. This lets a higher level in your program handle the error. Use it cautiously though, as it can make debugging tougher.

The Finally Block

The finally block serves as the dependable janitor in Java's exception-handling world. Regardless of how the try block exits (normally or due to an exception), the finally block is always guaranteed to execute. This ensures essential cleanup tasks are performed, even in the midst of errors.

Guaranteed Execution:

Imagine an exception erupts within the try block, and the program jumps to the corresponding catch block for handling. But what happens to resources opened within the try block, like files, network connections, or database handles? The finally block guarantees that the code within it will execute, regardless of how the try block exits (normally, with an exception, or even due to a return statement). This ensures proper cleanup and resource management, preventing potential leaks or inconsistencies.

Common Use Cases for the Finally Block:

The finally block proves invaluable in various scenarios:

  • Resource Cleanup: Closing files, network connections, database connections, or releasing other system resources acquired within the try block. This ensures they are properly released, even if an exception occurs.

try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {   // Read data from the file } finally {   // Guaranteed to close the reader, even if an exception occurs   if (reader != null) {     reader.close();   } }

  • Releasing Locks: Releasing locks acquired within the try block to prevent deadlocks. Even if an exception occurs, the lock will be released, allowing other threads to proceed.
  • Executing Essential Code: Running critical code that must execute regardless of exceptions, like logging error messages or updating internal state.

Limitations of the Finally Block:

The finally block is great for cleanup, but does not change program flow. Don't use it to return or throw exceptions after errors. Its job is to ensure essential tasks like closing files or freeing memory happen regardless of errors. This keeps your code clean and avoids resource leaks.

By understanding the guaranteed execution and use cases of the finally block, you can ensure your Java code handles exceptions gracefully while maintaining clean resource management practices. The next section will explore best practices for crafting robust exception-handling mechanisms using the try-catch-finally construct.

Mastering Exception Handling: 

Crafting robust exception handling goes beyond simply catching exceptions. Here are key practices to elevate your Java code:

  • Embrace Specific Exception Handling: While a generic catch (Exception e) block might seem convenient, it's often better to define separate catch blocks for specific exception types. This improves code readability and allows for targeted handling of different exceptions.
  • Declare Exceptions in Method Signatures: The throws keyword within a method signature allows you to declare the exceptions a method might throw. This informs callers about potential exceptions and encourages them to handle them appropriately.
  • Understand Checked vs. Unchecked Exceptions: Java differentiates between checked and unchecked exceptions. Checked exceptions (like IOException) must be declared in method signatures, forcing callers to consider them. Unchecked exceptions (like NullPointerException) bypass the try-catch mechanism and require more proactive handling throughout your code.
  • Leverage Automatic Resource Management (ARM): Java offers resources with built-in automatic closing (like try-with-resources). This simplifies resource management by ensuring proper cleanup, even in the face of exceptions. By utilizing ARM resources, you can often avoid explicit finally blocks for basic closing operations.

Advanced Exception Handling Techniques

The try-catch-finally construct offers a powerful foundation, but Java provides additional tools for complex scenarios:

  • Nested Try-Catch Blocks: You can nest try-catch blocks within each other. This allows for more granular exception handling within specific code sections. An inner try block can catch exceptions specific to its code, while an outer try block might handle broader exceptions.
  • Try-with-Resources for Automatic Cleanup: Introduced in Java 7, the try-with-resources statement simplifies resource management. It automatically closes resources upon exiting the try block (normally or due to an exception). This eliminates the need for explicit finally blocks for basic closing operations of resources like files, network connections, or database handles.
  • Exception Handling in Multithreading: When working with multiple threads, exceptions can become trickier. Java provides mechanisms like synchronized blocks and thread-safe collections to ensure data consistency even when exceptions occur. Additionally, you can propagate exceptions thrown by one thread to the main thread for handling.

Conclusion:

The try-catch-finally construct forms the cornerstone of exception handling in Java. The try block identifies code prone to exceptions, while catch blocks define how to handle specific exceptions that arise. The finally block ensures essential cleanup tasks happen regardless of how the try block exits.

Effective exception handling is key to robust Java code. Catch specific exceptions, leverage throws, and try-with-resources for cleaner code. This prevents crashes, improves error messages, and boosts overall code quality. Remember: handled exceptions are gracefully overcome!

About the Author

Ms. Anya Petrova

Qualification: Master's degree in Software Engineering

Expertise: Java security champion, building secure and robust back-end systems.

Research Focus: Investigate and implement cutting-edge Java security frameworks like Spring Security and OWASP libraries to mitigate vulnerabilities and prevent cyberattacks.

Experience: Develops secure back-end systems for mission-critical applications, employing threat modeling and secure coding practices.

Ms. Petrova's dedication to Java security ensures she crafts reliable and well-protected applications, safeguarding sensitive data and functionality.  

Share this post

Recent blogs.

Blog title

Java GUI Programming with Swing ... Read More

Mar 16, 2024

Blog title

JDBC Tutorial: Connecting to a Database in Java ... Read More

Mar 15, 2024

Blog title

Java Networking: Building Your First Socket Program ... Read More

Mar 14, 2024

Blog title

Multithreading in Java: A Beginner's Guide ... Read More

Blog title

Java Exception Handling: Try, Catch, Finally Explained ... Read More

Mar 13, 2024

Blog title

Java Collections Framework: A Comprehensive Guide ... Read More

Mar 12, 2024

Blog title

How to Debug Java Programs Like a Pro ... Read More

Blog title

The 10 Most Important Java Concepts You Need to Know ... Read More

Mar 11, 2024

The Programming Assignment Help - Instant and Affordable Coding Help from the Top-Rated Tutors!

Get help Now

java exception handling assignment

RuntimeException sub classes : Error sub classes : ArithmeticException ClassCirculatoryError ArrayIndexOutofBoundException ClassFormatError ArrayStoreException Error ClassCasteException IllegalAccessError IlegalArgumentException IncompatibleClassChangeError IndexOutofBoundException InstantiationError NegativeArraySizeException LinkageError NullPointerException NoCassDefFoundError NumberFormatException NoSuchFieldError SecurityException NoSuchMethodError StringIndexOutofBoundException OutofMemoryError StackOverflowError Exception sub classes: Throwable ClassNotFoundException UnknownError DataFormatException UnsatisfiedLinkError IllegalAccessException VerifyError InstantiationException VirtualMachineError InterruptedException NoSuchMethodException RuntimeException
try { // block of code } catch ( ExceptionType1 e) { // Exception handling routine for ExceptionType1 (optional) } catch (ExceptionType2 e ) { // Exception handling routine for ExceptionType2 (optional) } . . . catch (ExceptionType_n e) { // Exception handling routine for ExceptionType_n (optional) } finally { // Program code of exit (optional) }
C:\> java DivideZero // To run the Application DivideZero
One can notice the output then : Java . lang . Arithmetic Exception : / by zero at DivideZero.Any Function (DivideZero.Java : 3) at DivideZero.main (DivideZero.Java : 7)
int wrongMath ( ) { int n = 100; int result ; for (int i = 9; i > -1; i- - ) result = n % i; // modulo remainder. return (result ); }
void wrongArrayAccess ( ) { int anArray = new int[10] ; // An array of size having index 0,1,..,9 ��.. anArray[10] = 999 ; // index out of range }
void badArrayStore ( ) { int storeArray = new int[15]; // An array of integers boolean boolArray =new boolean[5]; // An array of booleans System.arraycopy(storeArray, 2, boolArrary, 2, 4); // Copy the element boolArray[3,4,5] into storeArray starting at storeArray[2] }
class ClassA { // a token of a simple class ��� } class ClassB extends ClassA{ // A sub class of ClassA ���. void bMethod ( ) { . . . . } } class Test { void wrongCast ( ) { ClassA anInstanceA = new ClassA( ); ClassB anInstanceB = (Class B ) anInstanceA; // Exception anInstanceB.bMethod ( ); } }
static void wrongArgumentPass (int agru ) { if (argu == 0) throw new IllegalArgumentException ( "Argument cannot be 0 "); int x = 555 / argu; }
Void negativeSizeArray ( ) { int theSize = -5; int foolArray = new int[theSize]; }
void nullPointer ( ) { String myString = null; // myString is a null reference object if ( myString.equals (" Sahara" )) { System.out.println (" Howz!"); } }
void wrongStringIndex ( ) { String theString = " N E R I S T", char theChar = theString.charat(20); // Index should be between 0 and 10 }
Practice 5.1 public class DivideZero { static int anyFunction (int x, int y ){ try { int a = x/y; return a; } catch (ArithmeticException e) { System.out.println ( "Division by zero" ); } return 0; } public static void main (String args[]) { int a,b, result; a=0; b=0; System.out.print("Enter any two integers : "); try{ a = System.in.read(); b = System.in.read(); }catch(Exception e){} result = anyFunction (a, b); System.out.println ( "Result : " + result); } } Find out the types of exceptions.
Practice 5.2 class CommandLineInput { public static void main (String args[ ] { int number, InvalidCount = 0; validCount = 0; for (int i = 0; i Find out the types of exceptions.
Practice 5.3 public class MultiCatch { public static void main (String args[ ]) { try { int i = args.length; // No of arguments in the command line String myString[] = new String[i]; // If i = 0 then myString null pointer error // #1 // if(myString[0].equals(�Java�)); System.out.println("First word is Java !"); System.out.println( " Number of arguments = " + i ); // # 2 // int x = 18/ i; int y[ ] = {555, 999}; // y is an array of size 2 and index are 0,1 // #3 // y[ i ] = x; // Index is out-of-range may occur if i > 1 } catch (ArithmeticException e ) { // To catch the error at #2 System.out.println ( " Div by 0 : "+ e ); } catch (NullPointerException e ) { // To catch the error at #1 System.out.println ( "A null pointer exception :" + e ); } catch (ArrayIndexOutOfBoundsException e ) { // To catch the error at #3 System.out.println ("Array Index OoB : " + e); } } } Find out the types of exceptions.
Practice 5.4 import java.lang.*; public class exceptions{ public static void main(String Args[]) throws Exception{ int[] array = new int[3]; try{ for (int i=0;i Find out the types of exceptions.
Practice 5.5 class ExceptionTest { public static int j; public static void main (String args[ ] ) { for (int i = 0; i Find out the types of exceptions.
Practice 5.6 // Use of finally in try-catch // class FinallyDemo { public static void main (String [ ] args ) { int i = 0; String greetings [ ] = { "Hello Twinkle !", "Hello Java !", "Hello World ! " }; while ( i Find out the types of exceptions.
Practice 5.7 // File Name BankDemo.java public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); System.out.println("\nWithdrawing $600..."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $"+ e.getAmount()); e.printStackTrace(); } } } // File Name CheckingAccount.java //create a separate class file and name it as CheckingAccount.java. Then paste the following class //contents there. public class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount Find out the types of exceptions.
Practice 5.8 import java.io.*; public class exceptionHandle{ public static void main(String[] args) throws Exception{ try{ int a,b; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); a = Integer.parseInt(in.readLine()); b = Integer.parseInt(in.readLine()); } catch(NumberFormatException ex){ System.out.println(ex.getMessage() + " is not a numeric value."); System.exit(0); } } } Find out the types of exceptions.
  • Separating Error Handling Code from "Regular" Code.
  • Propagating Errors Up the Call Stack.
  • Grouping Error Types and Error Differentiation.
  • List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.
  • Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked exceptions. Class Error and its subclasses also are unchecked.
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Solve Coding Problems
  • Java Tutorial

Overview of Java

  • Introduction to Java
  • The Complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works - JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?

Basics of Java

  • Java Basic Syntax
  • Java Hello World Program
  • Java Data Types
  • Primitive data type vs. Object data type in Java with Examples
  • Java Identifiers

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

  • How to Take Input From User in Java?
  • Scanner Class in Java
  • Java.io.BufferedReader Class in Java
  • Difference Between Scanner and BufferedReader Class in Java
  • Ways to read input from console in Java
  • System.out.println in Java
  • Difference between print() and println() in Java
  • Formatted Output in Java using printf()
  • Fast I/O in Java in Competitive Programming

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples
  • Java Assignment Operators with Examples
  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods

Access Modifiers in Java

  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java

Inheritance in Java

Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.

  • 'this' reference in Java
  • Inheritance and Constructors in Java
  • Java and Multiple Inheritance
  • Interfaces and Inheritance in Java
  • Association, Composition and Aggregation in Java
  • Comparison of Inheritance in C++ and Java
  • abstract keyword in java
  • Abstract Class in Java
  • Difference between Abstract Class and Interface in Java
  • Control Abstraction in Java with Examples
  • Difference Between Data Hiding and Abstraction in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • Difference between Inheritance and Polymorphism
  • Dynamic Method Dispatch or Runtime Polymorphism in Java
  • Difference between Compile-time and Run-time Polymorphism in Java

Constructors in Java

  • Copy Constructor in Java
  • Constructor Overloading in Java
  • Constructor Chaining In Java with Examples
  • Private Constructors and Singleton Classes in Java

Methods in Java

  • Static methods vs Instance methods in Java
  • Abstract Method in Java with Examples
  • Overriding in Java
  • Method Overloading in Java
  • Difference Between Method Overloading and Method Overriding in Java
  • Differences between Interface and Class in Java
  • Functional Interfaces in Java
  • Nested Interface in Java
  • Marker interface in Java
  • Comparator Interface in Java with Examples
  • Need of Wrapper Classes in Java
  • Different Ways to Create the Instances of Wrapper Classes in Java
  • Character Class in Java
  • Java.Lang.Byte class in Java
  • Java.Lang.Short class in Java
  • Java.lang.Integer class in Java
  • Java.Lang.Long class in Java
  • Java.Lang.Float class in Java
  • Java.Lang.Double Class in Java
  • Java.lang.Boolean Class in Java
  • Autoboxing and Unboxing in Java
  • Type conversion in Java with Examples

Keywords in Java

  • Java Keywords
  • Important Keywords in Java
  • Super Keyword in Java
  • final Keyword in Java
  • static Keyword in Java
  • enum in Java
  • transient keyword in Java
  • volatile Keyword in Java
  • final, finally and finalize in Java
  • Public vs Protected vs Package vs Private Access Modifier in Java
  • Access and Non Access Modifiers in Java

Memory Allocation in Java

  • Java Memory Management
  • How are Java objects stored in memory?
  • Stack vs Heap Memory Allocation
  • How many types of memory areas are allocated by JVM?
  • Garbage Collection in Java
  • Types of JVM Garbage Collectors in Java with implementation details
  • Memory leaks in Java
  • Java Virtual Machine (JVM) Stack Area

Classes of Java

  • Understanding Classes and Objects in Java
  • Singleton Method Design Pattern in Java
  • Object Class in Java
  • Inner Class in Java
  • Throwable Class in Java with Examples

Packages in Java

  • Packages In Java
  • How to Create a Package in Java?
  • Java.util Package in Java
  • Java.lang package in Java
  • Java.io Package in Java
  • Java Collection Tutorial

Exception Handling in Java

Exceptions in java.

  • Types of Exception in Java with Examples
  • Checked vs Unchecked Exceptions in Java
  • Java Try Catch Block
  • Flow control in try catch finally in Java
  • throw and throws in Java
  • User-defined Custom Exception in Java
  • Chained Exceptions in Java
  • Null Pointer Exception In Java
  • Exception Handling with Method Overriding in Java
  • Multithreading in Java
  • Lifecycle and States of a Thread in Java
  • Java Thread Priority in Multithreading
  • Main thread in Java
  • Java.lang.Thread Class in Java
  • Runnable interface in Java
  • Naming a thread and fetching name of current thread in Java
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java
  • Thread.sleep() Method in Java With Examples
  • Synchronization in Java
  • Importance of Thread Synchronization in Java
  • Method and Block Synchronization in Java
  • Lock framework vs Thread synchronization in Java
  • Difference Between Atomic, Volatile and Synchronized in Java
  • Deadlock in Java Multithreading
  • Deadlock Prevention And Avoidance
  • Difference Between Lock and Monitor in Java Concurrency
  • Reentrant Lock in Java

File Handling in Java

  • Java.io.File Class in Java
  • Java Program to Create a New File
  • Different ways of Reading a text file in Java
  • Java Program to Write into a File
  • Delete a File Using Java
  • File Permissions in Java
  • FileWriter Class in Java
  • Java.io.FileDescriptor in Java
  • Java.io.RandomAccessFile Class Method | Set 1
  • Regular Expressions in Java
  • Regex Tutorial - How to write Regular Expressions?
  • Matcher pattern() method in Java with Examples
  • Pattern pattern() method in Java with Examples
  • Quantifiers in Java
  • java.lang.Character class methods | Set 1
  • Java IO : Input-output in Java with Examples
  • Java.io.Reader class in Java
  • Java.io.Writer Class in Java
  • Java.io.FileInputStream Class in Java
  • FileOutputStream in Java
  • Java.io.BufferedOutputStream class in Java
  • Java Networking
  • TCP/IP Model
  • User Datagram Protocol (UDP)
  • Differences between IPv4 and IPv6
  • Difference between Connection-oriented and Connection-less Services
  • Socket Programming in Java
  • java.net.ServerSocket Class in Java
  • URL Class in Java with Examples

JDBC - Java Database Connectivity

  • Introduction to JDBC (Java Database Connectivity)
  • JDBC Drivers
  • Establishing JDBC Connection in Java
  • Types of Statements in JDBC
  • JDBC Tutorial
  • Java 8 Features - Complete Tutorial

Exception Handling in Java is one of the effective means to handle runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

What are Java Exceptions?

In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. This object is called the exception object. It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred.

Major reasons why an exception Occurs

  • Invalid user input
  • Device failure
  • Loss of network connection
  • Physical limitations (out-of-disk memory)
  • Code errors
  • Opening an unavailable file

Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control of the programmer, and we should not try to handle errors.

Difference between Error and Exception

Let us discuss the most important part which is the differences between Error and Exception that is as follows: 

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

Exception Hierarchy

All exception and error types are subclasses of the class Throwable , which is the base class of the hierarchy. One branch is headed by Exception . This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error is used by the Java run-time system( JVM ) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.

Exception Hierarchy in Java

Java Exception Hierarchy

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.

types of exceptions in Java

Exceptions can be categorized in two ways:

  • Checked Exception
  • Unchecked Exception 
  • User-Defined Exceptions

Let us discuss the above-defined listed exception that is as follows:

1. Built-in Exceptions

Built-in exceptions are the exceptions that are available in Java libraries. 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 unchecked exceptions are just opposite to the checked 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.
Note: For checked vs unchecked exception, see Checked vs Unchecked Exceptions  

2. User-Defined Exceptions:

Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called ‘user-defined Exceptions’. 

The advantages of Exception Handling in Java are as follows:

  • Provision to Complete Program Execution
  • Easy Identification of Program Code and Error-Handling Code
  • Propagation of Errors
  • Meaningful Error Reporting
  • Identifying Error Types

Methods to print the Exception information:

1. printStackTrace()

This method prints exception information in the format of the Name of the exception: description of the exception, stack trace.

2. toString() 

The toString() method prints exception information in the format of the Name of the exception: description of the exception.

3. getMessage()  

The getMessage() method prints only the description of the exception.

How Does JVM Handle an Exception?

Default Exception Handling: Whenever inside a method, if an exception has occurred, the method creates an Object known as an Exception Object and hands it off to the run-time system(JVM). The exception object contains the name and description of the exception and the current state of the program where the exception has occurred. Creating the Exception Object and handling it in the run-time system is called throwing an Exception. There might be a list of the methods that had been called to get to the method where an exception occurred. This ordered list of methods is called Call Stack . Now the following procedure will happen. 

  • The run-time system searches the call stack to find the method that contains a block of code that can handle the occurred exception. The block of the code is called an Exception handler .
  • The run-time system starts searching from the method in which the exception occurred and proceeds through the call stack in the reverse order in which methods were called.
  • If it finds an appropriate handler, then it passes the occurred exception to it. An appropriate handler means the type of exception object thrown matches the type of exception object it can handle.
  • If the run-time system searches all the methods on the call stack and couldn’t have found the appropriate handler, then the run-time system handover the Exception Object to the default exception handler , which is part of the run-time system. This handler prints the exception information in the following format and terminates the program abnormally .

Look at the below diagram to understand the flow of the call stack. 

Flow of class stack for exceptions in Java

Illustration:

program output

Let us see an example that illustrates how a run-time system searches for appropriate exception handling code on the call stack.

How Programmer Handle an Exception?

Customized Exception Handling: Java exception handling is managed via five keywords: try , catch , throw , throws , and finally . Briefly, here is how they work. Program statements that you think can raise exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch block) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.

Tip: One must go through control flow in try catch finally block for better understanding.   

Need for try-catch clause(Customized Exception Handling)

Consider the below program in order to get a better understanding of the try-catch clause.

program output

Output explanation: In the above example, an array is defined with size i.e. you can access elements only from index 0 to 3. But you trying to access the elements at index 4(by mistake) that’s why it is throwing an exception. In this case, JVM terminates the program abnormally . The statement System.out.println(“Hi, I want to execute”); will never execute. To execute it, we must handle the exception using try-catch. Hence to continue the normal flow of the program, we need a try-catch clause. 

How to Use the Try-catch Clause?

Certain key points need to be remembered that are as follows:     

  • In a method, there can be more than one statement that might throw an exception, So put all these statements within their own try block and provide a separate exception handler within their own catch block for each of them.
  • If an exception occurs within the try block, that exception is handled by the exception handler associated with it. To associate the exception handler, we must put a catch block after it. There can be more than one exception handler. Each catch block is an exception handler that handles the exception to the type indicated by its argument. The argument, ExceptionType declares the type of exception that it can handle and must be the name of the class that inherits from the Throwable class.
  • For each try block, there can be zero or more catch blocks, but only one final block.
  • The finally block is optional. It always gets executed whether an exception occurred in try block or not. If an exception occurs, then it will be executed after try and catch blocks.  And if an exception does not occur, then it will be executed after the try block. The finally block in Java is used to put important codes such as clean-up code e.g., closing the file or closing the connection.
  • If we write System.exit in the try block, then finally block will not be executed.

The summary is depicted via visual aid below as follows:  

Exceptions in Java

Related Articles:   

  • Types of Exceptions in Java
  • Checked vs Unchecked Exceptions
  • Throw-Throws in Java

Related Courses

Java Programming Foundation – Self Paced Course Find the right course for you to start learning Java Programming Foundation from the industry experts having years of experience. This Java Programming Foundation – Self Paced Course covers the fundamentals of the Java programming language, data types, operators and flow control, loops, strings , and much more. No more waiting! Start Learning JAVA Now and Become a Complete Java Engineer!

Please Login to comment...

  • Java-Exceptions
  • School Programming
  • WhatsApp To Launch New App Lock Feature
  • Top Design Resources for Icons
  • Node.js 21 is here: What’s new
  • Zoom: World’s Most Innovative Companies of 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Getting Started with Exception Handling in Java

1. what is exception handling, 2. why exceptions handling, 3. how does exception handling work in the jdk, other java exception handling tutorials:.

  • 5 Rules about Catching Exceptions in Java
  • How to create custom exceptions in Java
  • How to throw exceptions in Java - the differences between throw and throws
  • Java Checked and Unchecked Exceptions
  • Java exception API hierarchy - Error, Exception and RuntimeException
  • Understanding Exception Stack Trace in Java with Code Examples
  • Understanding Java Exception Chaining with Code Examples
  • What you may not know about the try-catch-finally construct in Java

About the Author:

java exception handling assignment

Add comment

   

Notify me of follow-up comments

Comments  

@

Javatpoint Logo

Exception Handling

JavaTpoint

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

hierarchy of exception handling

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:

  • Checked Exception
  • Unchecked Exception

hierarchy of exception handling

Difference between Checked and Unchecked Exceptions

1) checked exception.

The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords

Java provides five keywords that are used to handle the exception. The following table describes each.

Java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.

JavaExceptionExample.java

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.

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.

2) A scenario where NullPointerException occurs

If we have a null value in any variable , performing any operation on the variable throws a 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.

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. Consider the following statements.

Java Exceptions Index

  • Java Try-Catch Block
  • Java Multiple Catch Block
  • Java Nested Try
  • Java Finally Block
  • Java Throw Keyword
  • Java Exception Propagation
  • Java Throws Keyword
  • Java Throw vs Throws
  • Java Final vs Finally vs Finalize
  • Java Exception Handling with Method Overriding
  • Java Custom Exceptions

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Introduction to Java

  • What Is Java? A Beginner's Guide to Java and Its Evolution
  • Why Java is a Popular Programming Language?
  • Top 10 Reasons Why You Should Learn Java
  • Why Java is a Secure language?
  • What are the different Applications of Java?

Java for Android: Know the importance of Java in Android

  • What is the basic Structure of a Java Program?
  • What is the difference between C, C++ and Java?
  • Java 9 Features and Improvements
  • Top 10 Java Frameworks You Should Know
  • Netbeans Tutorial: What is NetBeans IDE and how to get started?

Environment Setup

  • How To Set Path in Java?
  • How to Write Hello World Program in Java?
  • How to Compile and Run your first Java Program?
  • Learn How To Use Java Command Line Arguments With Examples

Control Statements

  • What is for loop in java and how to implement it?
  • What is a While Loop in Java and how to use it?
  • What is for-each loop in Java?
  • What is a Do while loop in Java and how to use it?
  • What is a Switch Case In Java?

Java Core Concepts

  • Java Tutorial For Beginners – Java Programming Made Easy!
  • What are the components of Java Architecture?
  • What are Comments in Java? – Know its Types

What are Java Keywords and reserved words?

  • What is a Constructor in Java?
  • What is the use of Destructor in Java?
  • Know About Parameterized Constructor In Java With Examples
  • What are Operators in Java and its Types?
  • What Are Methods In Java? Know Java Methods From Scratch
  • What is Conditional Operator in Java and how to write it?
  • What is a Constant in Java and how to declare it?
  • What is JIT in Java? – Understanding Java Fundamentals
  • What You Should Know About Java Virtual Machine?
  • What is the role for a ClassLoader in Java?
  • What is an Interpreter in Java?
  • What is Bytecode in Java and how it works?
  • What is a Scanner Class in Java?

What is the Default Value of Char in Java?

  • this Keyword In Java – All You Need To Know
  • What is Protected in Java and How to Implement it?
  • What is a Static Keyword in Java?
  • What is an Array Class in Java and How to Implement it?
  • What is Ternary Operator in Java and how can you use it?
  • What is Modulus in Java and how does it work?
  • What is the difference between Method Overloading And Overriding?
  • Instance variable In Java: All you need to know
  • Know All About the Various Data Types in Java
  • What is Typecasting in Java and how does it work?
  • How to Create a File in Java? – File Handling Concepts
  • File Handling in Java – How To Work With Java Files?
  • What is a Comparator Interface in Java?
  • Comparable in Java: All you need to know about Comparable & Comparator interfaces
  • What is Iterator in Java and How to use it?
  • Java Exception Handling – A Complete Reference to Java Exceptions
  • All You Need to Know About Final, Finally and Finalize in Java
  • How To Implement Volatile Keyword in Java?
  • Garbage Collection in Java: All you need to know
  • What is Math Class in Java and How to use it?
  • What is a Java Thread Pool and why is it used?
  • Synchronization in Java: What, How and Why?
  • Top Data Structures & Algorithms in Java That You Need to Know
  • Java EnumSet: How to use EnumSet in Java?
  • How to Generate Random Numbers using Random Class in Java?
  • Generics in Java – A Beginners Guide to Generics Fundamentals
  • What is Enumeration in Java? A Beginners Guide
  • Transient in Java : What, Why & How it works?
  • What is Wait and Notify in Java?
  • Swing In Java : Know How To Create GUI With Examples
  • Java AWT Tutorial – One Stop Solution for Beginners
  • Java Applet Tutorial – Know How to Create Applets in Java
  • How To Implement Static Block In Java?
  • What is Power function in Java? – Know its uses
  • Java Array Tutorial – Single & Multi Dimensional Arrays In Java
  • Access Modifiers in Java: All you need to know
  • What is Aggregation in Java and why do you need it?
  • How to Convert Int to String in Java?
  • What Is A Virtual Function In Java?
  • Java Regex – What are Regular Expressions and How to Use it?

What is PrintWriter in Java and how does it work?

  • All You Need To Know About Wrapper Class In Java : Autoboxing And Unboxing
  • How to get Date and Time in Java?
  • What is Trim method in Java and How to Implement it?
  • How do you exit a function in Java?
  • What is AutoBoxing and unboxing in Java?
  • What is Factory Method in Java and how to use it?
  • Threads in Java: Know Creating Threads and Multithreading in Java
  • Join method in Java: How to join threads?
  • What is EJB in Java and How to Implement it?
  • What is Dictionary in Java and How to Create it?
  • Daemon Thread in Java: Know what are it's methods
  • How To Implement Inner Class In Java?
  • What is Stack Class in Java and how to use it?

Java Strings

  • What is the concept of String Pool in java?
  • Java String – String Functions In Java With Examples
  • Substring in Java: Learn how to use substring() Method
  • What are Immutable String in Java and how to use them?
  • What is the difference between Mutable and Immutable In Java?
  • BufferedReader in Java : How To Read Text From Input Stream
  • What are the differences between String, StringBuffer and StringBuilder?
  • Split Method in Java: How to Split a String in Java?
  • Know How to Reverse A String In Java – A Beginners Guide
  • What is Coupling in Java and its different types?
  • Everything You Need to Know About Loose Coupling in Java

Objects and Classes

  • Packages in Java: How to Create and Use Packages in Java?
  • Java Objects and Classes – Learn how to Create & Implement
  • What is Object in Java and How to use it?
  • Singleton Class in Java – How to Use Singleton Class?
  • What are the different types of Classes in Java?
  • What is a Robot Class in Java?
  • What is Integer class in java and how it works?
  • What is System Class in Java and how to implement it?
  • Char in Java: What is Character class in Java?
  • What is the Boolean Class in Java and how to use it?
  • Object Oriented Programming – Java OOPs Concepts With Examples
  • Inheritance in Java – Mastering OOP Concepts
  • Polymorphism in Java – How To Get Started With OOPs?
  • How To Implement Multiple Inheritance In Java?
  • Java Abstraction- Mastering OOP with Abstraction in Java
  • Encapsulation in Java – How to master OOPs with Encapsulation?
  • How to Implement Nested Class in Java?

What is the Use of Abstract Method in Java?

  • What is Association in Java and why do you need it?
  • What is the difference between Abstract Class and Interface in Java?
  • What is Runnable Interface in Java and how to implement it?
  • What is Cloning in Java and its Types?
  • What is Semaphore in Java and its use?
  • What is Dynamic Binding In Java And How To Use It?

Java Collections

  • Java Collections – Interface, List, Queue, Sets in Java With Examples
  • List in Java: One Stop Solution for Beginners
  • Java ArrayList: A Complete Guide for Beginners
  • Linked List in Java: How to Implement a Linked List in Java?
  • What are Vector in Java and how do we use it?
  • What is BlockingQueue in Java and how to implement it?
  • How To Implement Priority Queue In Java?
  • What is Deque in Java and how to implement its interface?
  • What are the Legacy Classes in Java?
  • Java HashMap – Know How to Implement HashMap in Java
  • What is LinkedHashSet in Java? Understand with examples
  • How to Implement Map Interface in Java?
  • Trees in Java: How to Implement a Binary Tree?
  • What is the Difference Between Extends and Implements in Java?
  • How to Implement Shallow Copy and Deep Copy in Java
  • How to Iterate Maps in Java?
  • What is an append Method in Java?
  • How To Implement Treeset In Java?
  • Java HashMap vs Hashtable: What is the difference?
  • How to Implement Method Hiding in Java
  • How To Best Implement Concurrent Hash Map in Java?
  • How To Implement Marker Interface In Java?

Java Programs

  • Palindrome in Java: How to check a number is palindrome?
  • How to check if a given number is an Armstrong number or not?
  • How to Find the largest number in an Array in Java?
  • How to find the Sum of Digits in Java?
  • How To Convert String To Date In Java?
  • Ways For Swapping Two Numbers In Java
  • How To Implement Addition Of Two Numbers In Java?
  • How to implement Java program to check Leap Year?
  • How to Calculate Square and Square Root in Java?
  • How to implement Bubble Sort in Java?
  • How to implement Perfect Number in Java?
  • What is Binary Search in Java? How to Implement it?
  • How to Perform Merge Sort in Java?
  • Top 30 Patterns in Java: How to Print Star, Number and Character
  • Know all about the Prime Number program in Java
  • How To Display Fibonacci Series In Java?
  • How to Sort Array, ArrayList, String, List, Map and Set in Java?
  • How To Create Library Management System Project in Java?
  • How To Practice String Concatenation In Java?
  • How To Convert Binary To Decimal In Java?
  • How To Convert Double To Int in Java?
  • How to convert Char to Int in Java?
  • How To Convert Char To String In Java?
  • How to Create JFrame in Java?

What is Externalization in Java and when to use it?

  • How to read and parse XML file in Java?
  • How To Implement Matrix Multiplication In Java?
  • How To Deal With Random Number and String Generator in Java?
  • Java Programs for Practice: Know the Simple Java Programs for Beginners

Advance Java

  • How To Connect To A Database in Java? – JDBC Tutorial
  • Advanced Java Tutorial- A Complete Guide for Advanced Java
  • Servlet and JSP Tutorial- How to Build Web Applications in Java?
  • Introduction to Java Servlets – Servlets in a Nutshell
  • What Is JSP In Java? Know All About Java Web Applications
  • How to Implement MVC Architecture in Java?
  • What is JavaBeans? Introduction to JavaBeans Concepts
  • Know what are the types of Java Web Services?

JavaFX Tutorial: How to create an application?

  • What is Executor Framework in Java and how to use it?
  • What is Remote Method Invocation in Java?
  • Everything You Need To Know About Session In Java?
  • Java Networking: What is Networking in Java?
  • What is logger in Java and why do you use it?
  • How To Handle Deadlock In Java?
  • Know all about Socket Programming in Java
  • Important Java Design Patterns You Need to Know About
  • What is ExecutorService in Java and how to create it?
  • Struts 2 Tutorial – One Stop Solution for Beginners
  • What is Hibernate in Java and Why do we need it?
  • What is Maven in Java and how do you use it?
  • What is Machine Learning in Java and how to implement it?

Career Opportunities

  • Java Developer Resume: How to Build an Impressive Resume?
  • What is the Average Java Developer Salary?

Interview Questions

  • Java Interview Questions and Answers
  • Top MVC Interview Questions and Answers You Need to Know in 2024
  • Top 50 Java Collections Interview Questions You Need to Know in 2024
  • Top 50 JSP Interview Questions You Need to Know in 2024
  • Top 50 Hibernate Interview Questions That Are A Must in 2024

Programming & Frameworks

Java exception handling – a complete reference to java exceptions.

java exception handling assignment

What is meant by exception handling?

Errors arise unexpectedly and can result in disrupting the normal flow of execution. This is something that every programmer faces at one point or the other while coding. Java,  being the most prominent  object-oriented language, provides a powerful mechanism to handle these errors/exceptions.

What happens if exceptions are not handled?

When an exception occurs, and if you don’t handle it, the program will terminate abruptly (the piece of code after the line causing the exception will not get executed).

Through this article on Java Exception Handling, I will give you a complete insight into the fundamentals and various methods of Exception Handling.

In this article, I will be covering the following topics.

Introduction to Exception Handling

  • Exceptions Hierarchy
  • Basic Exception Example

Types of Exceptions

  • Exception Handling Methods 
  • final  vs finally vs finalize 
  • throw vs throws

An exception is a problem that arises during the execution of a program. It can occur for various reasons say-

  • A user has entered an invalid data
  • File not found
  • A network connection has been lost in the middle of communications
  • The JVM has run out of a memory

Exception Handling mechanism follows a flow which is depicted in the below figure. But if an exception is not handled, it may lead to a system failure. That is why handling an exception is very important.

Next, begin by understanding the Exceptions Hierarchy.

Exceptions Hierarchy  

All exception and error types are subclasses of class  Throwable , which is the base class of hierarchy. One branch is headed by  Error which occurs at run-time and other by Exception that can happen either at compile time or run-time.

Now that you know what errors and exceptions are, let’s find out the basic difference between them. Take a look at the below table which draws a clear line between both of them.

Now,  we will dive deeper into exceptions and see how they can be handled. First, let’s see the different types of exceptions.

  • Checked Exception It is an exception that occurs at compile time, also called compile time exceptions. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using  throws  keyword.
  • Unchecked Exception It is an exception that occurs at the time of execution. These are also called  Runtime Exceptions.   In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to specify or catch the exceptions.

Basic Example of Exception

Above code represent an exception wherein inside try block we are going to write a code that may raise an exception and then, that exception will be handled in the catch block.        

Built-in Exceptions

User-defined exceptions.

Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, a user can also create exceptions which are called ‘User-Defined Exceptions’. Key points to note:

  • A user-defined exception must extend Exception class.
  • The exception is thrown using throw  keyword.

Subscribe to our youtube channel to get new updates..!

Now that you have seen the different types of exceptions, let’s dive deeper into this Java Exception Handling blog to understand various methods for handling these exceptions.

Exception Handling Methods

How to handle exceptions in java  .

As I have already mentioned, handling an exception is very important, else it leads to system failure. But how do you handle these exceptions?

Java provides various methods to handle the Exceptions like:

Let’s understand each of these methods in detail.

The try block contains a set of statements where an exception can occur. It is always followed by a catch block, which handles the exception that occurs in the associated try block. A try block must be followed by catch blocks or finally block or both.

Nested try block

try block within a try block is known as nested try block in java.

catch block

A catch block is where you handle the exceptions. This block must follow the try block and 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 a try block, the corresponding catch block that handles that particular exception executes. 

Multi-catch block

If you have to perform various tasks at the occurrence of various exceptions, you can use the multi-catch block.

finally block

A finally block  contains all the crucial statements that must be executed whether an exception occurs or not. The statements present in this block will always execute, regardless an exception occurs in the try block or not such as closing a connection, stream etc.

So, this was all about the various methods of handling exceptions.

You might have heard that final, finally and finalize are keywords in Java. Yes, they are, but they differ from each other in various aspects. So, let’s see how final, finally and finalize are different from each other with the help of below table.

final vs finally vs finalize

Similarly, throw & throws sound alike, but they are different from each other. Let’s see how, with the help of the below table.

throw vs throws 

This brings us to the end of our blog on Exception Handling in Java. I hope you found this blog informative and added value to your knowledge.

     

Check out the  Java Certification Training  by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Exception Handling” blog and we will get back to you as soon as possible.   

Recommended videos for you

Node js : steps to create restful web app, spring framework : introduction to spring web mvc & spring with bigdata, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, a day in the life of a node.js developer, node js express: steps to create restful web app, microsoft .net framework : an intellisense way of web development, ms .net – an intellisense way of web development, effective persistence using orm with hibernate, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, portal development and text searching with hibernate, php and mysql : server side scripting for web development, building web application using spring framework, implementing web services in java, rapid development with cakephp, create restful web application with node.js express, hibernate mapping on the fly, php & mysql : server-side scripting language for web development, nodejs – communication and round robin way, microsoft sharepoint-the ultimate enterprise collaboration platform, learn perl-the jewel of scripting languages, recommended blogs for you, everything you need to know about strings in c++, all you need to know about bootstrap gallery, top 10 most popular javascript frameworks, encapsulation in java – how to master oops with encapsulation, pointers in c, what is generics in java – a beginners guide, string in java – string functions in java with examples, top 50 html interview questions and answers in 2024, split in php: what is str_split() function, how to implement interface in php, top 50 spring interview questions you must prepare in 2024, removing elements from an array in javascript, spring mvc tutorial – everything you need to know, join the discussion cancel reply, trending courses in programming & frameworks, full stack web development internship program.

  • 29k Enrolled Learners
  • Weekend/Weekday

Java Certification Training Course

  • 75k Enrolled Learners

Python Scripting Certification Training

  • 14k Enrolled Learners

Flutter Application Development Course

  • 12k Enrolled Learners

Spring Framework Certification Course

Node.js certification training course.

  • 10k Enrolled Learners

Advanced Java Certification Training

  • 7k Enrolled Learners

Data Structures and Algorithms using Java Int ...

  • 31k Enrolled Learners

Microsoft .NET Framework Certification Traini ...

  • 6k Enrolled Learners

PHP & MySQL with MVC Frameworks Certifica ...

  • 5k Enrolled Learners

Browse Categories

Subscribe to our newsletter, and get personalized recommendations..

Already have an account? Sign in .

20,00,000 learners love us! Get personalised resources in your inbox.

At least 1 upper-case and 1 lower-case letter

Minimum 8 characters and Maximum 50 characters

We have recieved your contact details.

You will recieve an email from us shortly.

Instructions: Omitted

Getting Ready: Omitted

  • Open Example1.java in the editor (e.g. jGrasp).
  • Compile and execute the application Example1 .
  • What was output by the application when you executed it? The answer is: 2 Done.
  • Change the value of denominator to 0.
  • Re-compile and re-execute Example1 .
  • What "error" was generated by the application when you executed it? Exception in thread "main" java.lang.ArithmeticException: / by zero at Example1.main(Example1.java:11)
  • Why was this "error" generated at run-time (rather than at compile-time)? The compiler can not find errors that result from variables being assigned particular values (since the assignments do not take place until run time).
  • Add a try-catch statement. Specifically, put only the statement that generated the exception inside of the try block and put no statments in the catch block. (Hint: You should be able to determine what exception to catch and what line generated the exception from the error message that you received during the previous step.)
  • Re-compile Example1 .

This error is generated because ratio is initialized in the try block and this assignment will not take place if an exception is thrown before the assignment can be completed.

  • Move the "output statement" into the try block (as well).
  • Add the statement System.out.println("Divide by 0."); to the catch block.
  • What output was generated? Divide by 0. Done.
  • Add a call to the printStackTrace() method of the ArithmeticException to the end of the catch block.
  • What output was generated? Divide by 0. java.lang.ArithmeticException: / by zero at Example.main(Example.java:13) Done.
  • Did the application execute properly or not? Yes it did. An ArithmeticException was thrown when the division was attempted but it was caught. After it was caught some messages were printed and then the application terminated.
  • Open Example2.java in the editor (e.g. jGrasp). (Note: Different editors handle tabs/spaces differently. As a result, you may need to fix the indentation of files created by other people. In jGrasp you can do this by first generating a Control Structure Diagram ( F2 ) and then removing the CSD ( Shift - F2 ).)
  • Compile Example2 .
  • What error was generated? Example.java:20: variable i might not have been initialized numbers[i]+"/"+numbers[i+1]); ^
  • Initialize i to 0 inside of the try block (but before the for loop).
  • What error was generated? Example.java:21: variable i might not have been initialized numbers[i]+"/"+numbers[i+1]); ^
  • It is not possible for i to be used before it is initialized. Why is this error generated anyway? (Hint: Think about block statements.) The try block is treated as a single (block) statement. This block statement may throw an exception causing the catch block to be entered before the assignment is completed.
  • Move the initialization of i before the try block.
  • Compile and execute Example2 .
  • What output is generated? 100/10=10 Couldn't calculate 10/0
  • Why aren't all of the divisions even attempted? During iteration 1 of the loop an exception is thrown. When this happens control leaves the try block and enters the catch block. Control then leaves the catch block and then leaves main which causes the application to terminate.
  • Fix Example2 so that it executes properly. (Hint: Move the try-catch block inside of the for block.) What did you change? public class Example2 { public static void main(String[] args) { int i, ratio; int[] numbers = {100,10,0,5,2,8,0,30}; for (i=0; i < numbers.length-1; i++) { try { ratio = numbers[i] / numbers[i+1]; System.out.println(numbers[i]+"/"+numbers[i+1]+"="+ratio); } catch (ArithmeticException ae) } System.out.println("Couldn't calculate "+ numbers[i]+"/"+numbers[i+1]); } } } }
  • Compile and execute Example3 and verify that it outputs all of the values followed by the word "Done".
  • Modify Example3 so that it loops "properly" and does not need to use a try-catch statement. (Note: The output should not change.) What did you change? public class Example3 { public static void main(String[] args) { int i; int[] data = {50, 320, 97, 12, 2000}; for (i=0; i < data.length; i++) { System.out.println(data[i]); } } }
  • What functionality does a StringTokenizer object provide? It can be used to break a String into component parts, called tokens.
  • What are the three formal parameters of the explicit value constructor in the StringTokenizer class? The String that is going to be tokenized, the delimiters to use while tokenizing, and whether or not the delimiters should be returned as tokens.
  • Compile Example4.java .
  • Execute Example4 as follows: java Example4 5.3+9.2 .
  • What output is generated? Result: 14.5
  • Execute Example4 as follows: java Example4 5.3+ .
  • What output is generated? Invalid syntax
  • Why? In particular, what exception is thrown and why? A NoSuchElementException is thrown by the statement rightString = tokenizer.nextToken();
  • Execute Example4 as follows: java Example4 5.3+a .
  • What output is generated? One or more operands is not a number
  • Why? In particular, what exception is thrown and why? A NumberFormatException is thrown by the statement rightOperand = Double.parseDouble(rightString);
  • Modify Example4.java so that it supports addition (+), subtraction (-), multiplication (*), and division (/).
  • Modify Example4.java so that it processes all of the command line arguments rather than just args[0] . (Your program should treat each command line argument as a different expression to evaluate. So, for example, it should be able to be executed as follows: java Example4 5.0+4.1 3.2*9.1 .
  • Modify Example4.java so that it tells you which operand is not a number. (Hint: You may need to use nested try-catch blocks.) when

Copyright 2011

30+ Java Exception Handling Interview Questions And Answers

pramodbablad

  • April 14, 2023
  • Exception Handling , Java Interview Questions

11 Comments

Java exception handling is one of the favorite topic of the many interviewers to test the candidate’s basic Java skills. In this post, I have collected some of the likely Java exception handling interview questions which you may face in your technical interview. I hope it will help you.

30+ Most Asked Java Exception Handling Interview Questions And Answers

1) What is an exception?

Exception is an abnormal condition which occurs during the execution of a program and disrupts normal flow of a program. This exception must be handled properly. If it is not handled, program will be terminated abruptly.

2) How the exceptions are handled in Java? OR Explain exception handling mechanism in Java?

Exceptions in Java are handled using try, catch and finally blocks.

try block : The code or set of statements which are to be monitored for exception are kept in this block.

catch block : This block catches the exceptions occurred in the try block.

finally block : This block is always executed whether exception is occurred in the try block or not and occurred exception is caught in the catch block or not.

3) What is the difference between error and exception in Java?

Errors are mainly caused by the environment in which an application is running. For example, OutOfMemoryError happens when JVM runs out of memory. Where as exceptions are mainly caused by the application itself. For example, NullPointerException occurs when an application tries to access null object.

Click here to see more about Error Vs Exception in Java.

4) Can we keep other statements in between try, catch and finally blocks?

No. We shouldn’t write any other statements in between try, catch and finally blocks.

5) Can we write only try block without catch and finally blocks?

No, it shows compilation error. The try block must be followed by either catch block or finally block.

Note : From Java 7, with the introduction of try-with resources blocks, we can write only try block without catch and finally blocks provided resources must be AutoCloseable.

6) There are three statements in a try block – statement1, statement2 and statement3. After that there is a catch block to catch the exceptions occurred in the try block. Assume that exception has occurred in statement2. Does statement3 get executed or not?

No, statement3 is not executed. Once a try block throws an exception, remaining statements will not be executed. Control comes directly to catch block.

7) What is unreachable catch block error?

When you are keeping multiple catch blocks, the order of catch blocks must be from most specific to general ones. i.e sub classes of Exception must come first and super classes later. If you keep super classes first and sub classes later, compiler will show unreachable catch block error.

8) Explain the hierarchy of exceptions in Java?

Java Exception Handling Interview Questions And Answers

Click here to see more about hierarchy of exceptions in Java.

9) What are run time exceptions in Java. Give example?

The exceptions which occur at run time are called as run time exceptions. These exceptions are unknown to compiler. All sub classes of java.lang.RunTimeException and java.lang.Error are run time exceptions. These exceptions are unchecked type of exceptions. For example, NumberFormatException , NullPointerException , ClassCastException , ArrayIndexOutOfBoundException , StackOverflowError etc.

10) What is OutOfMemoryError in Java?

OutOfMemoryError is the sub class of java.lang.Error which occurs when JVM runs out of memory.

11) what are checked and unchecked exceptions in java?

Checked exceptions are the exceptions which are known to compiler. These exceptions are checked at compile time only. Hence the name checked exceptions. These exceptions are also called compile time exceptions. Because, these exceptions will be known during compile time itself.

Unchecked exceptions are those exceptions which are not at all known to compiler. These exceptions occur only at run time. These exceptions are also called as run time exceptions. All sub classes of java.lang.RunTimeException and java.lang.Error are unchecked exceptions.

Click here to see more about checked and unchecked exceptions.

12) What is the difference between ClassNotFoundException and NoClassDefFoundError in Java?

Click here to see more about ClassNotFoundException Vs NoClassDefFoundError in Java.

13) Can we keep the statements after finally block If the finally block is returning the control?

No, it gives unreachable code error. Because, control is returning from the finally block itself. Compiler will not see the statements after it. That’s why it shows unreachable code error.

14) Does finally block get executed If either try or catch blocks are returning the control?

Yes, finally block will be always executed no matter whether try or catch blocks are returning the control or not.

15) Can we throw an exception manually? If yes, how?

Yes, we can throw an exception manually using throw keyword. Syntax for throwing an exception manually is

throw InstanceOfThrowableType;

Below example shows how to use throw keyword to throw an exception manually.

16) What is Re-throwing an exception in Java?

Exceptions raised in the try block are handled in the catch block. If it is unable to handle that exception, it can re-throw that exception using throw keyword. It is called re-throwing an exception.

17) What is the use of throws keyword in Java?

throws keyword is used to specify the exceptions that a particular method can throw. The syntax for using throws keyword is,

Click here to see the uses of throws keyword in Java.

18) Why it is always recommended that clean up operations like closing the DB resources to keep inside a finally block?

Because finally block is always executed whether exceptions are raised in the try block or not and raised exceptions are caught in the catch block or not. By keeping the clean up operations in finally block, you will ensure that those operations will be always executed irrespective of whether exception is occurred or not.

19) What is the difference between final, finally and finalize in Java?

Click here to see more details about the differences between final, finally and finalize in Java.

20) How do you create customized exceptions in Java?

Click here to see about customized exceptions in Java.

21) What is ClassCastException in Java?

ClassCastException is a RunTimeException which occurs when JVM is unable to cast an object of one type to another type.

22) What is the difference between throw, throws and throwable in Java?

Click here to see more about throw, throws and throwable in Java.

23) What is StackOverflowError in Java?

StackOverflowError is an error which is thrown by the JVM when stack overflows.

24) Can we override a super class method which is throwing an unchecked exception with checked exception in the sub class?

No. If a super class method is throwing an unchecked exception, then it can be overridden in the sub class with same exception or with any other unchecked exceptions but can not be overridden with checked exceptions.

25) What are chained exceptions in Java?

Click here to see about chained exceptions in Java.

26) Which class is the super class for all types of errors and exceptions in Java?

java.lang.Throwable is the super class for all types of errors and exceptions in Java.

27) What are the legal combinations of try, catch and finally blocks?

28) What is the use of printStackTrace() method?

printStackTrace() method is used to print the detailed information about the exception occurred.

29) Give some examples to checked exceptions?

ClassNotFoundException, SQLException, IOException

30) Give some examples to unchecked exceptions?

NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException

31) Do you know try-with-resources blocks? Why do we use them? When they are introduced?

Try-with-resources blocks are introduced from Java 7 to auto-close the resources like File I/O streams, Database connection, network connection etc… used in the try block. You need not to close the resources explicitly in your code. Try-with-resources implicitly closes all the resources used in the try block.

32) What are the benefits of try-with-resources?

The main benefit of try-with-resources is that it avoids resource leaks that could happen if we don’t close the resources properly after they are used. Another benefit of try-with-resources is that it removes redundant statements in the code and thus improves the readability of the code.

33) What are the changes made to exception handling from Java 7?

Multi-catch exceptions and try-with-resources are two major changes made to exception handling from Java 7. Click here to see Java 7 exception handling changes.

34) What are the improvements made to try-with-resources in Java 9?

Click here to see the improvements made to try-with-resources in Java 9.

35) What are the differences between StackOverflowError and OutOfMemoryError In Java?

Also Read :

  • Java Exception Handling Cheat Sheet

Java Exception Handling Quiz

  • Java Strings Interview Questions
  • Java Array Interview Questions
  • Java Inheritance Interview Questions
  • Interview Questions On main()
  • Interview Questions On final keyword
  • 110+ Java Interview Programs
  • 15 Simple but confusing interview questions
  • 40+ Core Java Coding Q&A
  • 25+ simple basic Java interview questions
  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to email a link to a friend (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to share on Telegram (Opens in new window)

Related Posts

Java 8 interview sample coding questions.

  • June 26, 2023

Java Array Interview Questions And Answers

  • April 23, 2023
  • December 13, 2022

What design pattern is used to implement exception handling features in most languages? plz reply..

it is chain of responsibility design pattern

Chain Of Responsibility Pattern

5) Can we write only try block without catch and finally blocks? Yes, From java 7 onwards, if a class implements AutoCloseable interface, then it could be used as an argument in the try section and then it is not compulsory to have catch or finally block. Please refer to the below example. Here Scanner class implements AutoCloseable interface.

public class Test{ public static void main(String[] args) { //After the completion of try block, the scanner object would be auto closed. try(Scanner sc = new Scanner(System.in)){ System.out.println(sc.hashCode()); } } }

5) Yes , In Java 7 with the introduction of try with resources concept , we are able to write try block without catch and finally blocks. The only constraint is the resources which we are declaring as try block parameter must implements Autocloseable interface. A resource is said to be Autocloseable if and only if corresponding class implements java.lang.Autocloseable interface.

consider following example snipped try{ int a = 10/0; // statement 1 }catch(ArithmeticException ae){ // handle code } My question is – exception arise at statement 1 but how java internally identify that exception is ArithmeticException or else ?

When an exception occurs inside a Java method, the method creates an Exception object and passes the Exception object to the JVM (in Java term, the method ” throw ” an Exception ). The Exception object contains the type of the exception, and the state of the program when the exception occurs.

Consider the following code snippet.

void method () { statement1; try { statement2; } catch (Exception e) { //Exception Handling code } statement3; } If statement1, statement2 and statement3 all throw exceptions, catch block can handle exceptions thrown by which statement[s]?

if all statements throws exceptions then program will terminated at statement1. And if statement1 is not throwing any kind of exception then catch block will handle statement2’s exception.

Catch block executes whenever a statement failed to execute in try block, any statement which failed to execute then it will directly throw an exception to catch block and won’t execute next statement.

Site is Awesome!…

Leave a Reply Cancel Reply

Name  *

Email  *

Add Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

Post Comment

IMAGES

  1. Java Exception Handling with Examples

    java exception handling assignment

  2. Java Exception Handling Tutorial. Understanding Java Exception Handling

    java exception handling assignment

  3. What is Exception Handling in Java?

    java exception handling assignment

  4. Java Exception Handling Example Tutorial

    java exception handling assignment

  5. How to handle Exception in Java?

    java exception handling assignment

  6. Java Exception Handling with Examples

    java exception handling assignment

VIDEO

  1. Java Exception Handling For Certification & Interviews __ Java Exception Handling __ by Durga Sir

  2. what is Exception in java with example

  3. Exception Handling Explanation with an Example Program in Java (HINDI)

  4. Java Exception handling basics &demo

  5. Introduction to Exception Handling in JAVA Lecture-32

  6. Java Exception Handling

COMMENTS

  1. Exception Handling in Java

    at Exceptions.getPlayers(Exceptions.java:12) <-- Exception arises in getPlayers() method, on line 12. at Exceptions.main(Exceptions.java:19) <-- getPlayers() is called by main(), on line 19. Copy. Without handling this exception, an otherwise healthy program may stop running altogether! We need to make sure that our code has a plan for when ...

  2. Java Exception Handling (With Examples)

    3. Java throw and throws keyword. The Java throw keyword is used to explicitly throw a single exception.. When we throw an exception, the flow of the program moves from the try block to the catch block.. Example: Exception handling using Java throw class Main { public static void divideByZero() { // throw an exception throw new ArithmeticException("Trying to divide by 0"); } public static void ...

  3. Java Exception Handling Assignment

    Java Exception Handling Assignment. Ask Question Asked 10 years, 1 month ago. Modified 2 years, 11 months ago. Viewed 3k times 0 So I've recently learned exception handling for Java and I'm still trying to get used to it and all but I feel like I'm missing something. I was doing an assignment for my class and the compiler doesn't like my code.

  4. Exception Handling in Java: A Complete Guide with Best and Worst Practices

    Exception Handling in Java: A Complete Guide with Best and Worst Practices. David Landup. Overview. Handling Exceptions in Java is one of the most basic and fundamental things a developer should know by heart. Sadly, this is often overlooked and the importance of exception handling is underestimated - it's as important as the rest of the code.

  5. Java Exception Handling: Try, Catch, Finally Explained

    Java's try-catch-finally structure helps manage them gracefully. The try block holds error-prone code, while catch blocks define actions for specific exceptions. Finally, the finally block executes code regardless of errors, often for cleanup tasks. This approach prevents crashes, maintains program flow, and protects data integrity, leading to ...

  6. Java Exception Handling

    It includes try, catch, and finally block, as well as chained exceptions and logging exercises. 1. Write a Java program that throws an exception and catch it using a try-catch block. 2. Write a Java program to create a method that takes an integer as a parameter and throws an exception if the number is odd. 3.

  7. Java Exception Handling: 20 Best Practices for Error-Free Code

    This post is another addition to the best practices series available in this blog. In this post, we cover some well-known and little-known practices that we must consider while handling exceptions in our next java programming assignment. 1. Inbuilt Exceptions in Java. Before we dive into deep concepts of exception-handling best practices, let ...

  8. Chapter 5 -- Exception Handling in Java

    Assignment; Q&A. Introduction. This Chapter discusses exceptions handling mechanism in Java. An exception is an abnormal condition that can occur during the execution time of a program. If these exceptions are not prevented or at least handled properly, either the program will be aborted abnormally, or the incorrect result will be carried on. ...

  9. Exception Handling in Java: A Developer's Handbook

    Java Exception Handling Best Practices. Here are some expert tips to help you ride the waves of exceptions seamlessly. Tips for Effective Exception Handling in Java. Catch Specific Exceptions: Always catch the most specific exception class possible. This allows you to handle different exception scenarios with precision and ensures that ...

  10. Java Exception Handling: How to Specify and Handle Exceptions

    How to Specify an Exception. If you don't handle an exception within a method, it will be propagated within the call stack. And if it's a checked exception, you also need to specify that the method might throw the exception. You can do that by adding a throws clause to the method declaration.

  11. Exceptions in Java

    In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program's instructions. Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. This object is called the exception object.

  12. Getting Started with Exception Handling in Java

    By applying exception handling, you will make your programs more reliable, more stable, and most importantly, produce good quality software applications. Having said that, handling exceptions should be your habit in your daily coding. And now, we are about to see how it is implemented in the Java programming language. 3.

  13. 9 Best Practices to Handle Java Exceptions

    2. Prefer Specific Exceptions. The more specific the exception that you throw is, the better. Always keep in mind that a coworker who doesn't know your code (or maybe you in a few months) may need to call your method and handle the exception. Therefore make sure to provide them as much information as possible.

  14. Java Exceptions Interview Questions (+ Answers)

    The throws keyword is used to specify that a method may raise an exception during its execution. It enforces explicit exception handling when calling a method: public void simpleMethod() throws Exception { // ... } The throw keyword allows us to throw an exception object to interrupt the normal flow of the program. This is most commonly used when a program fails to satisfy a given condition:

  15. Java Exception Interview Questions and Answers

    14. Provide some Java Exception Handling Best Practices? Some of the best practices related to Java Exception Handling are: Use Specific Exceptions for ease of debugging. Throw Exceptions Early (Fail-Fast) in the program. Catch Exceptions late in the program, let the caller handle the exception.

  16. Exception Handling in Java

    Java provides five keywords that are used to handle the exception. The following table describes each. 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.

  17. Exception Handling in Java

    Introduction to Exception Handling. An exception is a problem that arises during the execution of a program. It can occur for various reasons say-. A user has entered an invalid data. File not found. A network connection has been lost in the middle of communications. The JVM has run out of a memory.

  18. Lab: Experimenting with Exception Handling

    An Inappropriate Use of Exception Handling: This part of the lab considers an inappropriate use of exception handling and how to "fix" it. Compile and execute Example3 and verify that it outputs all of the values followed by the word "Done". Modify Example3 so that it loops "properly" and does not need to use a try-catch statement.

  19. 30+ Java Exception Handling Interview Questions And Answers

    30+ Most Asked Java Exception Handling Interview Questions And Answers. 1) What is an exception? Exception is an abnormal condition which occurs during the execution of a program and disrupts normal flow of a program. This exception must be handled properly. If it is not handled, program will be terminated abruptly.

  20. Handling Advanced Exceptions in Java

    In this lesson, you will expand upon Java exception handling using try and catch functionality. Learn to throw and catch several exceptions: array out of bounds, file not found, etc. Updated: 11 ...

  21. java

    Exception Handling for college assignment. Ask Question Asked 7 years ago. Modified 7 years ago. Viewed 97 times ... Exception Handling Java. 0. Java Exception Handling Assignment. 0. Exception handling fix. Hot Network Questions GBP OIS Curve - Zero Rate Curve Calculation in Quantlib