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.

Answer from itwasntme on Stack Overflow
🌐
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
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.

Discussions

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
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
Result object vs throwing exceptions
The most common case is when there ... in Java when it happens the input data is bounced back with an IllegalArgumentException. ... You should try to never return exceptions unless there is no other option. The problem with standard error handling is that you just throw something ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
February 12, 2020
java - How to manage exceptions in a long call stack - Software Engineering Stack Exchange
When throw a exception inside java method, IntelliJ suggest to add exception to method signature. When I have a long call-stack as below how I manage these exceptions. method 1() -> method 2() -... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
🌐
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.
🌐
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.
🌐
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.
🌐
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.
Find elsewhere
🌐
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.
🌐
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
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 › javarevisited › how-to-throw-exceptions-in-java-using-throw-throws-keywords-throwing-exceptions-7082007f6462
How To Throw Exceptions In Java Using throw, throws Keywords | Throwing Exceptions | by Mouad Oumous | Javarevisited | Medium
February 22, 2024 - There are many differences between throw and throws keywords. A list of differences between throw and throws are given below: Java throw keyword is used throw an exception explicitly in the code, inside the function or the block of code.
🌐
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.
🌐
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
🌐
Quora
quora.com › In-Java-when-you-use-a-Throw-Exception-are-you-skipping-over-bad-code-to-allow-the-program-to-continue-running-or-when-would-it-be-used-for
In Java, when you use a Throw Exception, are you skipping over bad code to allow the program to continue running or when would it be used for? - Quora
Answer (1 of 3): Here’s an excellent writeup on the use and misuse of exceptions: Vexing exceptions Personally, I tend to catch exception in one of two places: immediate outside the function that throws it (these would be the ‘vexing’ exceptions from the above article), or at the very top of the...
🌐
W3Schools
w3schools.com › java › ref_keyword_throw.asp
Java throw Keyword
The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.
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.

Top answer
1 of 12
89

You have to distinguish between return values and errors.

A return value is one of many possible outcomes of a computation. An error is an unexpected situation which needs to be reported to the caller.

A module may indicate that an error occurred with a special return value or it throws an exception because an error was not expected. That errors occur should be an exception, that's why we call them exceptions.

If a module validates lottery tickets, the outcome may be:

  • you have won
  • you have not won
  • an error occurred (e.g. the ticket is invalid)

In case of an error, the return value is neither "won" nor "not won", since no meaningful statement can be made when e.g. the lottery ticket is not valid.

Addendum

One might argue that invalid tickets are a common case and not an error. Then the outcome of the ticket validation will be:

  • you have won
  • you have not won
  • the ticket is invalid
  • an error occurred (e.g. no connection to the lottery server)

It all depends on what cases you are planning to support and what are unexpected situations where you do not implement logic other than to report an error.

2 of 12
75

This is a good question that professional developers have to consider carefully. The guideline to follow is that exceptions are called exceptions because they are exceptional. If a condition can be reasonably expected then it should not be signaled with an exception.

Let me give you a germane example from real code. I wrote the code which does overload resolution in the C# compiler, so the question I faced was: is it exceptional for code to contain overload resolution errors, or is it reasonably expected?

The C# compiler's semantic analyzer has two primary use cases. The first is when it is "batch compiling" a codebase for, say, a daily build. The code is checked in, it is well-formed, and we're going to build it in order to run test cases. In this environment we fully expect overload resolution to succeed on all method calls. The second is you are typing code in Visual Studio or VSCode or another IDE, and you want to get IntelliSense and error reports as you're typing. Code in an editor is almost by definition wrong; you wouldn't be editing it if it were perfect! We fully expect the code to be lexically, syntactically and semantically wrong; it is by no means exceptional for overload resolution to fail. (Moreover, for IntelliSense purposes we might want a "best guess" of what you meant even if the program is wrong, so that the IDE can help you correct it!)

I therefore designed the overload resolution code to always succeed; it never throws. It takes as its argument an object representing a method call and returns an object which describes an analysis of whether or not the call is legal, and if not legal, which methods were considered and why each was not chosen. The overload resolver does not produce an exception or an error. It produces an analysis. If that analysis indicates that a rule has been violated because no method could be chosen, then we have a separate class whose job it is to turn call analyses into error messages.

This design technique has numerous advantages. In particular, it allowed me to easily unit-test the analyzer. I feed it inputs that I've analyzed "by hand", and verify that the analysis produced matches what I expected.


Can we assume that the user entered the correct credentials and throw an exception when the credentials are invalid, or should we expect to get some sort of LoginResult object?

Your question here is about what I think of as "Secure Code" with capitals. All code should be secure code, but "Secure Code" is code that directly implements aspects of a security system. It is important to not use rules of thumb/tips and tricks/etc when designing Secure Code because that code will be the direct focus of concerted attacks by evildoers who seek to harm your user. If someone manages to sneak wrong code past my overload resolution detector, big deal, they compile a wrong program. But if someone manages to sneak past the login code, you have a big problem on your hands.

The most important thing to consider when writing Secure Code is does the implementation demonstrate resistance to known patterns of attack, and that should inform the design of the system.

Let me illustrate with a favourite example. Fortunately this problem was detected and eliminated before the first version of .NET shipped, but it did briefly exist within Microsoft.

"If something unexpected goes wrong in the file system, throw an exception" is a basic design principle of .NET. And "exceptions from the file system should give information about the file affected to assist in debugging" is a basic design principle. But the result of these sensible principles was that low-trust code could produce and then catch an exception where the message was basically "Exception: you do not have permission to know the name of file C:\foo.txt".

The code was not initially designed with a security-first mindset; it was designed with a debuggability-first mindset, and that often is at cross-purposes to security. Consider that lesson carefully when designing the interface to a security system.

🌐
Baeldung
baeldung.com › home › java › core java › exception handling in java
Exception Handling in Java | Baeldung
May 11, 2024 - Now, there are times when we have code that needs to execute regardless of whether an exception occurs, and this is where the finally keyword comes in. In our examples so far, there ‘s been a nasty bug lurking in the shadows, which is that Java by default won’t return file handles to the operating system. Certainly, whether we can read the file or not, we want to make sure that we do the appropriate cleanup! ... public int getPlayerScore(String playerFile) throws FileNotFoundException { Scanner contents = null; try { contents = new Scanner(new File(playerFile)); return Integer.parseInt(contents.nextLine()); } finally { if (contents != null) { contents.close(); } } }
🌐
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 5
4

It doesn’t matter one bit how long the call stack is.

Method A calls method B which could throw an exception. Method A has three choices: It can be written in such a way that it can let an exception pass through to its own caller without code handling it at all. Or it can catch the exception, handle it completely and not pass it on - that’s what you do if you know how to handle the exception. Or it catches the exception, takes actions to make its own code work fine, and retries the exception, possibly modified. That’s what you need to do.

Now if you have a long call chain, that just means that you may have more methods that can throw exceptions. You need to do the steps that I described in each method that calls another method that can throw.

Important: Any method that has no exception handling code must be written in such a way that everything works fine if an exception is passed through. That’s the developer’s job. Garbage collection in Java and destructors for stack variables in C++ help.

2 of 5
3

Us usual, there is no single best way.

What IntelliJ suggests (and it offers more options than just adding it to the method signature) are only ways that are simple mechanical fixes.

We'd need to more know about your project, your architecture, etc. to determine what the best approach for your software, given your current knowledge would be. That approach may change tomorrow though when you learn something new or get other requirements.

Generally, I commend you for recognizing the simple solution as a bad idea. Yes, just adding throws declarations to hundreds of methods certainly isn't a very appealing solution. In order to find other approaches to error handling, there are a few guiding questions you can ask:

  • What sort of error are you thinking about here? Is it an inconvenience, does it reduce the service's capabilities, does it outright crash and stop your software from working,...
  • Who is this error relevant to? Is it something the user needs to see, or something that operations needs to know about, or will only developers be interested in it?
  • How should the error be treated? Is it enough to just catch an exception and do some logging? do you need to dynamically modify your program behavior (f.ex. to work around a 3rd party service being offline)? do you need to translate your error into some other domain (f.ex. turn an authorization-related exception to the proper HTTP error code)

After you got an idea to the answers for these questions, there's a whole other bunch of questions you can ask to narrow down the best technical solution. Read up on different error handling approaches if you don't already know a bunch of them - here's just a starter: Validation/Either objects (or more generally monads), HTTP filters, checked or unchecked exceptions, ... and then there's a whole line of thinking on how to design your programs such that things you thought about as "error" become normal and need not even be treated in any exceptional way.

🌐
Reddit
reddit.com › r/experienceddevs › catching errors vs throwing, is there a standard or best practice in enterprise java services?
r/ExperiencedDevs on Reddit: Catching errors vs throwing, is there a standard or best practice in enterprise java services?
December 5, 2023 -

I'm building a backend java service in an enterprise setting. There are a few errors I know the application will throw so I've caught them in the code and am logging an error level message with a bit of information about the transaction that caused the error.

I'm wondering if this is the best option or if I should also be throwing the error. Our APM (dynatrace) does not have application log access so I'm assuming it won't know about log messages even if they are errors but I have yet to confirm this with the necessary people at my org. Ideally I want dynatrace to know when these errors are occurring so it will reflect in the reported application error rate.

Edit: secondary question that comes up as I think more about this and get replies...should error level log statements contribute to dynatraces error rate metrics? I would hope so but it's my first time using it so just want to make sure my assumptions are right.