🌐
Study.com
study.com › computer programming › programming languages › compiled languages › java (programming language)
Exceptions in Java: Definition & Example | Study.com
November 26, 2024 - There is a Throwable class (which lets Java throw the exception), from which comes the all-important Exception class. In turn there is a whole slate of sub-classes that all inherit from Exception. These include the arithmetic (divide by zero), file, and array exceptions shown earlier. To unlock this lesson you must be a Study.com Member. Create your account · Let's look at a couple of examples of exceptions. We'll start with the divide by zero error, since it can happen very easily in code that crunches numbers.
🌐
Sentry
blog.sentry.io › exception-handling-in-java-with-real-examples
Exception Handling in Java (with Real Examples) | Product Blog • Sentry
July 15, 2025 - In its simplest form, it consists of two blocks of code, one in which we attempt some operation that we know to be prone to exceptions (try), and another in which we handle any exception that arises (catch). It looks something like this: ... Here’s a more concrete example, dealing with an attempt to read a file that does not exist. ... import java.io.*; public class Example { public static void main(String[] args) { try { System.out.println("Reading file..."); FileReader reader = new FileReader("nonexistentfile.txt"); System.out.println("Successfully read file."); } catch (FileNotFoundException e) { System.out.println("The file was not found!"); } } }
Discussions

EXCEPTION HANDLING!!
It’s easier to think of exceptions as things that can’t be known to be good ahead of time and maybe where there’s no graceful way to continue moving forward even if you were to resume the normal flow of execution. Imagine your program tries to connect to a database, but the database is down or not there. This isn’t something the end user can resolve, and it’s not something the program can fix on its own. There’s no way forward. This is a good candidate for an exception. Also, resuming where you left off shouldn’t be too tough, if it’s a thing that’s recoverable in some way (usually by retrying later). Bad user input should be caught earlier and not result in exceptions. Programs often do so for expediency, but it’s not a good practice for many reasons that I won’t get into here. Bad user input is easily recoverable, and the program should validate that before we get into a state where an exception gets thrown. But at the end of the day, if bad data makes it into a function that can’t handle that data, all that function “knows” is that it can’t proceed. It doesn’t and shouldn’t know that its user entered data and that it can’t be tried again. Functions should be small and focused and try to do as little as possible, and they should throw exceptions when it’s impossible to accomplish their goal. More on reddit.com
🌐 r/javahelp
35
8
March 12, 2025
Exception handling in Java: Advanced features and types
The article has some errors. And not the throwable kind, heh: If not found, it unwinds the method-call stack looking for the closest catch block that can handle the exception. If not found, the JVM terminates with a suitable message. You can see this action in Listing 1. The part in italics is incorrect! What happens if there is no catch block that is suitable is that the thread exits and passes the exception that was never caught to the thread's uncaught exception handler. And that's that. The thread is done. By default, each thread starts with an uncaught exception handler that simply prints the exception to syserr (e.printStackTrace(); - that's the whole body, that's all). At no point does it ever exit a JVM. Of course, if you have a java app that never starts any threads, then the main thread is the only relevant thread, and if that exits due to an exception bubbling all the way up, yeah, sure, the JVM then exits as no non-daemon threads are running. But it feels ridiculous to handwave this away as 'oh we are just trying to keep it simple'. "The thread dies" is just as simple and much more accurate. You can invoke printStackTrace() directly, typically from a catch block. For example, consider a second version of the PrintStackTraceDemo application. This entire article keeps making pointless and misleading sidenotes. For example, it sidenotes 'you can also call printStackTrace(somePrintWriter) which is weird to mention; anybody can look at the API docs and discover this, and it's not like they're covering the entire API here. It's like I'm pointing out all the interesting aspects of the Mona Lisa and then casually remark: "Oh, look, someone dropped a candy wrapper over there. Anyway, moving right along..." - it's just bizarre to mention this. It strongly insinuates that this is important. And that then blows up thoroughly in the quoted section: Newbies are legendary in writing catch blocks with e.printStackTrace(); in it which is a massive anti-pattern that is difficult to eradicate. And this blog post is making it worse by using it as a way to explain that you can invoke printStackTrace yourself (not an important lesson!) without explaining that you shouldn't do that or that this contrived example shouldn't be taken as an insinuation of: "Ah, and this is how you write your standard catch block". Try-with-resources Another example that is fucking horrible. You don't deal with IOExceptions thrown by close() methods by ignoring them!! streams buffer. Any exception thrown by a close() method means the entire write operation has likely failed. If you treat them differently than any exception that would have been thrown by the most recent write call you wrote a hard-to-test for bug (i.e: A really really bad bug). But that isn't obvious here. It's again teaching extremely bad patterns. Listing 8. Copy.java No, the right way to deal with exceptions thrown here is to just declare your main method as throws Exception which you should almost always do. Writing a catch block that tosses most of the useful info in the garbage (as in this snippet, the exception's type which might be FileAccessDeniedException or whatnot - the key info, you toss that away!), then just writes something and blindly continues with the app is ON ERROR RESUME NEXT level stupidity. Common stupidity, but that shouldn't be an excuse. On the contrary, given that the common-ness has proven that your average new java programmer will readily misunderstand, you should go out of your way not to perpetuate this mistake. As is, this article should be torched with a flamethrower: If you send this to new java programmers and they read it, they'll be stupider after having read it than before. The article is fixable though. Come up with less 'actively perpetuating really stupid anti-patterns' examples, stop trying to be opinion-less (because the chosen examples and focus invoke an opinion, whether you intended it or not, and right now it's invoking the wrong ones), and cut some of the irrelevant chaff such as how to make your own stack trace (not relevant for an intro article in any way and actively misleads in suggesting that it is somehow an important tool one should be using often) and mentioning irrelevant parts of the API. More on reddit.com
🌐 r/java
9
17
May 30, 2024
Exception Handling in Java: A Complete Guide with Best and Worst Practices
Paging u/davidlandup In the logging and throwing section, it's probably worth mentioning that sometimes you want to add extra context to your situation, in which case it's a good idea to wrap the exception in a custom exception with that information. I'd also mention that because exceptions are just Java classes, you can create custom fields inside them to record all the required information. For example, if you have a AccessDeniedException you could create a constructor that takes a username and name of the resource they tried to access, as well as any additional message. More on reddit.com
🌐 r/java
6
18
September 17, 2018
My personal definitive guide to (java) Exceptions
I finally went on and wrote what i felt like i had to say in the context of exceptions. Since it's such a debated topic, i fully expect some negative backlash, and i have no problem with it, everybody is entitled to their opinion! Let me know if you find it somehow useful. More on reddit.com
🌐 r/java
62
41
January 5, 2021
People also ask

What is exception handling in Java
divException Handling is a way of handling errors that occur during runtime and compile timediv
🌐
scholarhat.com
scholarhat.com › home
What is Exception Handling in Java?: try, catch, throw, finally
What are the types of exceptions in Java
divJava exceptions are classified into two categories checked compiletime checked and uncheckedruntimediv
🌐
scholarhat.com
scholarhat.com › home
What is Exception Handling in Java?: try, catch, throw, finally
What are the 5 keywords in Java exception handling
divtry catch throw throws and finally are the five keywords used in Java exception handlingdiv
🌐
scholarhat.com
scholarhat.com › home
What is Exception Handling in Java?: try, catch, throw, finally
🌐
DataCamp
datacamp.com › doc › java › throw
throw Keyword in Java: Usage & Examples
In this example, the checkAge method throws an Exception if the provided age is less than 18. The main method calls checkAge within a try block and catches the exception, printing the error message.
🌐
ScholarHat
scholarhat.com › home
What is Exception Handling in Java?: try, catch, throw, finally
In this Java tutorial, we'll discuss exceptions and their types in Java, exception handling keywords like try, catch, throw, throws, and finally, with examples, exception hierarchy, differences between errors and exceptions, the final, finally, and finalize keywords, etc.
Published   September 9, 2025
🌐
GeeksforGeeks
geeksforgeeks.org › java › types-of-exception-in-java-with-examples
Types of Exception in Java with Examples - GeeksforGeeks
July 23, 2025 - IllegalStateException : This exception will throw an error or error message when the method is not accessed for the particular operation in the application. It comes under the unchecked exception. A. Arithmetic exception ...
🌐
Vlabs
java-iitd.vlabs.ac.in › exp › exceptions › theory.html
Exception Handling in Java - Virtual Labs
Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code... A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler.
🌐
Programiz
programiz.com › java-programming › exception-handling
Java Exception Handling (With Examples)
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0 at Main.divideByZero(Main.java:5) at Main.main(Main.java:9) 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.
Find elsewhere
🌐
Great Learning
mygreatlearning.com › blog › it/software development › exception handling in java with examples – 2025
Exception Handling in Java with Examples | 2025 - Great Learning
January 6, 2025 - Example: ArithmeticException, NullPointerException etc. Exception Handling in java is managed via five keywords: try, catch, throw, throws, and finally.
🌐
Pluralsight
pluralsight.com › blog › software development
How to handle the 10 most common exceptions in Java | Online Courses, Learning Paths, and Certifications - Pluralsight
July 17, 2024 - When investigating, consider turning up logging to see the exact SQL query in question. SQLException is also thrown by the Java API for formulating and transmitting queries. For example, ResultSet throws it when you try to read a non-queried column. And PreparedStatement throws this exception when your application sets a non-existent bind variable:
🌐
TheServerSide
theserverside.com › tip › Fix-these-10-common-examples-of-the-RuntimeException-in-Java
Fix these 10 common examples of the RuntimeException in Java | TheServerSide
The ArrayStoreException shares similarities with the ClassCastException. This Java runtime exception happens when the wrong type of object is placed into an array. In the example below, a BigInteger array is created, followed by an attempt to add a Double.
Published   March 16, 2022
🌐
w3resource
w3resource.com › java-exercises › exception › index.php
Java Exception Handling - Exercises, Solutions, and Practices
May 23, 2025 - This section covers how to catch and handle exceptions. It includes try, catch, and finally block, as well as chained exceptions and logging exercises. ... Write a Java program that throws an exception and catch it using a try-catch block.
🌐
Medium
medium.com › @ahmed.abdelfaheem › checked-and-unchecked-exceptions-in-java-6cb1c9815d32
Checked and Unchecked Exceptions in Java | by Ahmed Safwat | Medium
August 12, 2023 - Some common examples of checked exceptions in Java include: IOException: Thrown when an input or output operation fails, such as file I/O errors. SQLException: Thrown when there is an issue with database connectivity or queries.
🌐
W3Schools
w3schools.com › java › java_try_catch.asp
Java Exceptions (Try...Catch)
The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:
🌐
Tutorialspoint
tutorialspoint.com › java › java_exceptions.htm
Java - Exceptions
You need to understand them to know how exception handling works in Java. ... A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be ignored, the programmer should take care of (handle) these exceptions. For example, if you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception.
🌐
DigitalOcean
digitalocean.com › community › tutorials › exception-handling-in-java
Exception Handling in Java | DigitalOcean
October 6, 2022 - These exceptions are hard to debug, and we might need to look into each place where we are using that resource to make sure we are closing it. In Java 7, one of the improvements was try-with-resources where we can create a resource in the try statement itself and use it inside the try-catch block. When the execution comes out of the try-catch block, the runtime environment automatically closes these resources. Here is an example of the try-catch block with this improvement:
🌐
Baeldung
baeldung.com › home › java › core java › exception handling in java
Exception Handling in Java | Baeldung
May 11, 2024 - Oracle’s documentation tells us to use checked exceptions when we can reasonably expect the caller of our method to be able to recover. A couple of examples of checked exceptions are IOException and ServletException.
🌐
Rollbar
rollbar.com › home › java exceptions hierarchy explained
Java Exceptions Hierarchy Explained | Rollbar
May 15, 2025 - The diagram below shows the standard ... may need to handle. Examples of exceptions include IllegalArgumentException, ClassNotFoundException and NullPointerException....
🌐
Raygun
raygun.com › blog › java-exceptions-terminology
Java exceptions: Common terminology with examples · Raygun Blog
October 25, 2022 - Exception throwing in Java happens with the throw statement. ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, and IOException in our examples were all thrown automatically by the Java platform.
🌐
Java Programming
java-programming.mooc.fi › part-11 › 3-exceptions
Exceptions - Java Programming
Now the exception is thrown to ... to be thrown occurs. The throw command throws an exception. For example a NumberFormatException can be done with command throw new NumberFormatException()....
🌐
GeeksforGeeks
geeksforgeeks.org › java › exceptions-in-java
Java Exception Handling - GeeksforGeeks
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their it's exceptions. ... Built-in Exception are pre-defined exception classes provided by Java to handle common errors during program execution.
Published   3 weeks ago