Right, the way I understood try {} and catch {} as an absolute beginner was. Every time you write code and you are working with some sort of information. For example, lets say make a simple application that asks the user to enter a number (integer) and then you print out the number they have entered. The problem is if they enter a string when you are only accepting integers as your datatype. you now need to catch that problem so it doesn't crash the application. Example: public static void main(String[] args) { Scanner get_input = new Scanner(System.in) ; //With this line we create a new object called "get_input". System.out.print("Please enter a number: ") ; // We ask the user to enter a number int theNumber = get_input.nextInt(); // We read the number the user enters and we store it a variable. System.out.print("Your number was " + theNumber); // we print out their number. } This would all work fine but if they entered a word like "hello" instead of a number like 12 the program would crash. that's why we use the keyword try. try{ // the code here int theNumber = get_input.nextInt(); // We read the number the user enters and we store it a variable. }catch(Exception e) // if something goes wrong in the "try" block above we take the error message and we store it in the variable e { System.out.print("Please enter a valid number."); } here is also a video tutorial https://youtu.be/K_-3OLkXkzY Answer from Deleted User on reddit.com
🌐
W3Schools
w3schools.com › java › ref_keyword_throws.asp
Java throws Keyword
The throws keyword indicates what exception type may be thrown by a method. There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.
🌐
Rollbar
rollbar.com › home › how to throw exceptions in java
How to Throw Exceptions in Java | Rollbar
2 weeks ago - The detailMessage parameter gives the details of the message for this exception, and the throwable parameter gives the cause of this exception. The key takeaway: every exception needs a message explaining what went wrong, and optionally a cause pointing to the underlying exception that triggered it. Java’s built-in exceptions don’t always provide the information we need.
Discussions

When to throw an exception? When to try and catch and exception.
Right, the way I understood try {} and catch {} as an absolute beginner was. Every time you write code and you are working with some sort of information. For example, lets say make a simple application that asks the user to enter a number (integer) and then you print out the number they have entered. The problem is if they enter a string when you are only accepting integers as your datatype. you now need to catch that problem so it doesn't crash the application. Example: public static void main(String[] args) { Scanner get_input = new Scanner(System.in) ; //With this line we create a new object called "get_input". System.out.print("Please enter a number: ") ; // We ask the user to enter a number int theNumber = get_input.nextInt(); // We read the number the user enters and we store it a variable. System.out.print("Your number was " + theNumber); // we print out their number. } This would all work fine but if they entered a word like "hello" instead of a number like 12 the program would crash. that's why we use the keyword try. try{ // the code here int theNumber = get_input.nextInt(); // We read the number the user enters and we store it a variable. }catch(Exception e) // if something goes wrong in the "try" block above we take the error message and we store it in the variable e { System.out.print("Please enter a valid number."); } here is also a video tutorial https://youtu.be/K_-3OLkXkzY More on reddit.com
🌐 r/javahelp
19
10
June 9, 2018
What does Throwing an exception mean?
Throwing an exception is literally yeeting the current stack frame, and hoping the one outside of it can handle it. If I have functions foo and bar, like the following: def foo() { bar(); } def bar() { throw new Exception(); } Bar throws the exception, and it closes the current stack frame (the stack frame created when bar is called), and lets Foo try to handle it (the stack frame which called bar). As you know, the only way foo can handle the exception is by having a try { bar(); } catch { ... } block. I apologise that my example code is in Python, but hopefully this maps closely enough to C# that you understand what I'm trying to say :) More on reddit.com
🌐 r/csharp
69
79
November 8, 2020
How can I throw a general exception in Java? - Stack Overflow
As you can see in the first class, I have added a comment ("// throw exception") where I would like to throw an exception. Do I have to define my own class for exceptions or is there some general exception class in Java I can use? More on stackoverflow.com
🌐 stackoverflow.com
java - Why is "throws Exception" necessary when calling a function? - Stack Overflow
Similarly, if Method3 is not handling the exception in its body then, it had to define throws Exception in its method definition to give heads up its calling method. extension of the previous comment ... In Java, as you may know, exceptions can be categorized into two: One that needs the throws ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › java › throw-throws-java
throw and throws in Java - GeeksforGeeks
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception.
Published   August 5, 2025
🌐
Rollbar
rollbar.com › home › how to use the throws keyword in java (and when to use throw)
When and Why to Use Throw vs Throws in Java Exception Handling | Rollbar
September 16, 2024 - As seen in the syntax above, all ... should be separated by a comma in the declaration. The throw keyword in Java is used for explicitly throwing a single exception....
🌐
Sentry
sentry.io › sentry answers › java › how to throw exceptions in java
How to Throw Exceptions in Java | Sentry
October 21, 2022 - To throw an exception, we need to specify the keyword throws along with the exception type and any additional arguments the relevant exception constructor will accept.
🌐
YouTube
youtube.com › alex lee
Throw And Throws In Java Tutorial #48 - YouTube
$1,000 OFF ANY Springboard Tech Bootcamps with my code ALEXLEE. See if you qualify for the JOB GUARANTEE! 👉 https://bit.ly/3HX970hIn this video, I show you ...
Published   August 3, 2023
Views   37K
Find elsewhere
🌐
W3Schools
w3schools.com › java › java_try_catch.asp
Java Exceptions (Try...Catch)
assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while Java String Methods
🌐
Reddit
reddit.com › r/javahelp › when to throw an exception? when to try and catch and exception.
r/javahelp on Reddit: When to throw an exception? When to try and catch and exception.
June 9, 2018 -

Hello, I am lookign for a clear example of when you throw an exception and how to use it do you catch that thrown exception somewhere or does it end there. When do you use try and catch block for exceptions? I understand the concept of exceptions but that part isn't very clear to me. One method throws it other method catches it and so on.

Top answer
1 of 4
6
Right, the way I understood try {} and catch {} as an absolute beginner was. Every time you write code and you are working with some sort of information. For example, lets say make a simple application that asks the user to enter a number (integer) and then you print out the number they have entered. The problem is if they enter a string when you are only accepting integers as your datatype. you now need to catch that problem so it doesn't crash the application. Example: public static void main(String[] args) { Scanner get_input = new Scanner(System.in) ; //With this line we create a new object called "get_input". System.out.print("Please enter a number: ") ; // We ask the user to enter a number int theNumber = get_input.nextInt(); // We read the number the user enters and we store it a variable. System.out.print("Your number was " + theNumber); // we print out their number. } This would all work fine but if they entered a word like "hello" instead of a number like 12 the program would crash. that's why we use the keyword try. try{ // the code here int theNumber = get_input.nextInt(); // We read the number the user enters and we store it a variable. }catch(Exception e) // if something goes wrong in the "try" block above we take the error message and we store it in the variable e { System.out.print("Please enter a valid number."); } here is also a video tutorial https://youtu.be/K_-3OLkXkzY
2 of 4
2
I see a lot words in the comments. The way I see it is pretty simple. If the error is fatal / unrecoverable or if you're building an API and expect the user to catch the errors, you throw it. If you can correct the error in your UI then you should catch it, ex. your app opens files but the file specified can't be found, catch the error and bring up a UI prompt for the user to select a new file.
🌐
Reddit
reddit.com › r/csharp › what does throwing an exception mean?
r/csharp on Reddit: What does Throwing an exception mean?
November 8, 2020 -

I understand try, catch, and finally. But what does throw mean and how would i use it?

Top answer
1 of 19
119
Throwing an exception is literally yeeting the current stack frame, and hoping the one outside of it can handle it. If I have functions foo and bar, like the following: def foo() { bar(); } def bar() { throw new Exception(); } Bar throws the exception, and it closes the current stack frame (the stack frame created when bar is called), and lets Foo try to handle it (the stack frame which called bar). As you know, the only way foo can handle the exception is by having a try { bar(); } catch { ... } block. I apologise that my example code is in Python, but hopefully this maps closely enough to C# that you understand what I'm trying to say :)
2 of 19
13
Imagine you have a media library applicaiton. In that application, there is class called MediaItem, and it has a property called Rating. Rating is of data type int. But it's only allowed to have values between 1 and 5. So what should your class do when another piece of code somewhere tries to set the Rating to 6? The answer is that it should throw an exception. An exception means that something has gone wrong, and the method can't finish doing what it's supposed to do. That might be beacuse the caller did something wrong (as in my example). Or it might mean something internal has gone wrong. Or something external has gone wrong such as the network connection is down or the disk is full. For whatever reason, if your method can't do what it's supposed to do, it should probably throw an exception. So, some code: class MediaItem { private int _rating; public int Rating { get { return _rating; } set { if (value < 1 || value > 5) { throw new ArgumentOutOfRangeException(); } _rating = value; } } } Note that, as soon as you throw an exception, the current flow of the program stops. It does not carry on doing the next instruction. In the example above, it does not set Rating to a new value. If your method has a try/catch block, it will exceute the catch, then carry on with whatever comes after that. If your method does not have a try block, the method will end, and the method that called your method gets a chance to handle the exception. If this method has a try/catch block, it will execute the catch, then carry on with whatever comes after that. And if not, the thing that called that method gets a chance to handle the exception. And so on, all the way up the call stack. Note that I've talked about methods, but properties (as in my code example) work in exactly the same way, and you can view the two is being interchangeable for the purpose of this discussion. I've also not mentioned finally blocks, purely in order to simplify the post. If ther are finally blocks present, nothing changes at all except that the finally block executes. If the finally block has a catch block to go with it, the catch happens first, then the finally, then the code that comes after the finally. And if there is no catch block, the finally block runs, then the method ends and the thing that called the method runs, because the exception has not been caught. As for when you should throw - as a general rule, throw if something exceptional has happened which means you can't continue doing what you need to do. Don't throw for things that are expected, rather than exceptional. You shouldn't throw if the user enters something invalid, for example - that's not exceptional, it's to be expected. In the MediaItem example, I'd expect that the user interface should check if the rating is between 1 and 5. If not, it should show an error to the user (no exceptions needed here). If it is, it should set the Rating property on the MediaItem. This means that if the Rating is ever set to something outside the expected range, something has actually gone wrong in your code, it's not just that the user has entered something silly - and that's why it's appropriate to throw an exception here.
🌐
DataCamp
datacamp.com › doc › java › throw
throw Keyword in Java: Usage & Examples
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code.
🌐
Princeton
cs.princeton.edu › courses › archive › spr96 › cs333 › java › tutorial › java › exceptions › throwing.html
How to Throw Exceptions
Before you can catch an exception, some Java code somewhere must throw one. Any Java code can throw an exception: your code, code from a package written by someone else (such as the packages that come with the Java development environment), or the Java runtime system.
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › declaring.html
Specifying the Exceptions Thrown by a Method (The Java™ Tutorials > Essential Java Classes > Exceptions)
If the writeList method doesn't catch the checked exceptions that can occur within it, the writeList method must specify that it can throw these exceptions. Let's modify the original writeList method to specify the exceptions it can throw instead of catching them.
🌐
Pluralsight
pluralsight.com › blog › software development
How to throw an exception in Java | Online Courses, Learning Paths, and Certifications - Pluralsight
December 6, 2023 - What you are seeing right now is the exception and its stack trace, or the exact line where the exception was thrown followed by the series of method calls that led to that line. This is helpful for debugging purposes, but not likely helpful to your end user. We can improve this situation by handling the exception. Consider an improved version of `readLine` that keeps asking the user until they provide valid input: java private static Double readDouble(Console console, String message) { while (true) { Double value = Double.valueOf(console.readLine(message)); if (value is valid) { return value; } else { System.err.println(“Sorry, that input was invalid, please try again”); } } }
🌐
Medium
medium.com › @AlexanderObregon › java-exception-handling-throws-vs-try-catch-94b0abe1080d
Java Exception Handling — Throws vs. Try-Catch
March 17, 2024 - Exceptions are events that disrupt the normal flow of a program’s execution, and Java provides mechanisms to manage these disruptions gracefully. Two primary ways to handle exceptions are by using the try-catch blocks and declaring exceptions in method signatures with the throws keyword.
Top answer
1 of 9
191

In Java, as you may know, exceptions can be categorized into two: One that needs the throws clause or must be handled if you don't specify one and another one that doesn't. Now, see the following figure:

In Java, you can throw anything that extends the Throwable class. However, you don't need to specify a throws clause for all classes. Specifically, classes that are either an Error or RuntimeException or any of the subclasses of these two. In your case Exception is not a subclass of an Error or RuntimeException. So, it is a checked exception and must be specified in the throws clause, if you don't handle that particular exception. That is why you needed the throws clause.


From Java Tutorial:

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Now, as you know exceptions are classified into two: checked and unchecked. Why these classification?

Checked Exception: They are used to represent problems that can be recovered during the execution of the program. They usually are not the programmer's fault. For example, a file specified by user is not readable, or no network connection available, etc., In all these cases, our program doesn't need to exit, instead it can take actions like alerting the user, or go into a fallback mechanism(like offline working when network not available), etc.

Unchecked Exceptions: They again can be divided into two: Errors and RuntimeExceptions. One reason for them to be unchecked is that they are numerous in number, and required to handle all of them will clutter our program and reduce its clarity. The other reason is:

  • Runtime Exceptions: They usually happen due to a fault by the programmer. For example, if an ArithmeticException of division by zero occurs or an ArrayIndexOutOfBoundsException occurs, it is because we are not careful enough in our coding. They happen usually because some errors in our program logic. So, they must be cleared before our program enters into production mode. They are unchecked in the sense that, our program must fail when it occurs, so that we programmers can resolve it at the time of development and testing itself.

  • Errors: Errors are situations from which usually the program cannot recover. For example, if a StackOverflowError occurs, our program cannot do much, such as increase the size of program's function calling stack. Or if an OutOfMemoryError occurs, we cannot do much to increase the amount of RAM available to our program. In such cases, it is better to exit the program. That is why they are made unchecked.

For detailed information see:

  • Unchecked Exceptions — The Controversy
  • The Catch or Specify Requirement
2 of 9
35

Java requires that you handle or declare all exceptions. If you are not handling an Exception using a try/catch block then it must be declared in the method's signature.

For example:

class throwseg1 {
    void show() throws Exception {
        throw new Exception();
    }
}

Should be written as:

class throwseg1 {
    void show() {
        try {
            throw new Exception();
        } catch(Exception e) {
            // code to handle the exception
        }
    }
}

This way you can get rid of the "throws Exception" declaration in the method declaration.

🌐
JetBrains
blog.jetbrains.com › idea › 2024 › 03 › easy-hacks-how-to-throw-java-exceptions
Easy Hacks: How to Throw Java Exceptions | The IntelliJ IDEA Blog
March 12, 2024 - Note that this is also true for exceptions that may occur in third-party code, such as java.nio. In the following screenshot, you’ll see the readString method may throw an IOException, and IntelliJ IDEA again suggests either adding the exception to the method signature (throws IOException) or handling the exception using a try/catch block.
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › throwing.html
How to Throw Exceptions (The Java™ Tutorials > Essential Java Classes > Exceptions)
The pop method checks to see whether any elements are on the stack. If the stack is empty (its size is equal to 0), pop instantiates a new EmptyStackException object (a member of java.util) and throws it. The Creating Exception Classes section in this chapter explains how to create your own exception classes.
Top answer
1 of 1
3

Your current method covers the first point - to take an exception as parameter.
The throws Exception is unnecessary if you dont throw it from a method, but it is needed to cover the second point.

As commenters pointed, you just need to use the throw keyword to throw an exception, so the method could look like:

public void throwException (Exception ex) throws Exception {
    //some other code maybe?
    throw ex;
}

This implementation has a little flaw. When the null is passed as a parameter to it, the method will throw a NullPointerException, because the throw keyword accepts objects of the Throwable class or its subclasses (Exception is a subclass of Throwable).
To avoid NullPointerException (which is an unchecked-exception), simple if statement can be used:

public void throwException (Exception ex) throws Exception {
    if (ex != null) {
        throw ex;
    }
    //just for presentation,below it throws new Exception
    throw new Exception("ex parameter was null");
}

Edit:
As @Slaw suggested, in that very small case adding the null-check and throwing new Exception just disguises the NullPointerException. Without the null-check and throw new... the NPE will be thrown from that method and its stacktrace will show exact line of throw ex when the null is passed to that method.
The NPE is a subtype of RuntimeException class and the subtypes of RuntimeException doesn't need to be explicitly declared in method signature when they are thrown from that method. Like here:

public static void throwNPE(Exception e) {
    throw new NullPointerException();
}

The RuntimeException and its subclasses are called an unchecked-exceptions. Other classes extending one of Exception or Throwable classes are call checked-exceptions, because if a method throws them, it must declare that exception (or superclass) in the signature or explicitly try-catch it.

The proper use of null-check would be when the method would throw a more specific kind of exception (like IOException or a new subclass of Exception/Throwable) and the when the other method using the one which throws that new type of Exception would try-catch that specific type the NPE wouldn't be caught.

Just for good practices, when dealing with try-catch it's much better to catch exact types of thrown Exceptions instead of general Exception/Throwable. It helps to understand the real cause of exception, debug and fix code.