🌐
TutorialsPoint
tutorialspoint.com › how-to-print-custom-message-instead-of-errorstacktrace-in-java
How to print custom message instead of ErrorStackTrace in java?
import java.util.Scanner; class MyException extends Exception{ public MyException(String msg){ super(msg); } } public class PrintingExceptionMessage { public static void main(String args[]) throws Exception { String msg = "This is my custom exception"; Scanner sc = new Scanner(System.in); System.out.println("Enter first number: "); int a = sc.nextInt(); System.out.println("Enter second number: "); int b = sc.nextInt(); try { int c = a/b; System.out.println("The result is: "+c); }catch(ArithmeticException e) { MyException exce = new MyException(msg); throw exce; } } }
Discussions

Help with throwing custom exception (Homework)
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
4
1
January 29, 2021
How to Create and Handle a Custom Exception in Java - LambdaTest Community
What is the correct way to create a Java custom exception? I want to define my own exception type and throw it when a specific condition is met. For example, in a try block, I read a string using reader.readLine(), and if the string contains a space, I need to throw my custom exception. More on community.lambdatest.com
🌐 community.lambdatest.com
0
March 16, 2025
design patterns - Is it a good practice to use self-defined exception? - Software Engineering Stack Exchange
However, a better rule of the thumb for whether to have custom exceptions is to consider what the caller will do about it when the exception gets thrown. If you have three erroneous situations that are handled in three very different ways, it makes sense to have three types because then the caller can have three catch blocks accordingly. The alternative, which is to inspect the message ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 23, 2018
How do you structure your exception classes?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/java
33
44
January 17, 2024
🌐
Medium
medium.com › @nweligalla › creating-custom-exceptions-in-java-ea77a61fcaf4
Creating Custom Exceptions in Java | by Nayana Weligalla | Medium
January 31, 2024 - Now, when you throw it, you can include a message with the exception that caused it. public void withdrawFunds(double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException("Insufficient funds", ...
🌐
Alvin Alexander
alvinalexander.com › java › java-custom-exception-create-throw-exception
Java: How to create and throw a custom exception | alvinalexander.com
August 4, 2024 - As you can see, all you need to do to throw your custom exception is (1) create a new instance of the exception (new AlsCustomException("Anything but zero ...")), and then (2) throw that exception with the throw keyword. With those two pieces in place, we'll create a "driver" class with a main ...
🌐
DZone
dzone.com › data engineering › databases › implementing custom exceptions in java
Implementing Custom Exceptions in Java
November 13, 2017 - /** * The MyBusinessException wraps all checked standard Java exception and enriches them with a custom error code. * You can use this code to retrieve localized error messages and to link to our online documentation. * * @author TJanssen */ public class MyBusinessException extends Exception { ... } Quite often, your code catches a standard exception before you throw ...
🌐
Scaler
scaler.com › topics › custom-exception-in-java
Java Custom Exception - Scaler Topics
June 23, 2024 - We try to give a path to Stream for the file in the try-catch block. If the file exists, try block will execute. In case the file is not present, inside the catch block we throw a custom exception in java that makes the program more readable. We print StackTrace and message in the output.
🌐
Hero Vired
herovired.com › home › learning-hub › topics › custom-exceptions-in-java
How to Create Custom Exceptions in Java - Hero Vired
January 20, 2025 - ... Override the toString() method to customise the error message. @Override public String toString() { return "MyCustomException: " + getMessage(); } This makes your exception message more readable.
Find elsewhere
🌐
TechVidvan
techvidvan.com › tutorials › java-custom-exception
Java Custom Exception - TechVidvan
November 10, 2023 - In the main method, we call processInput with “invalid” input. Since the input is indeed “invalid”, the customuncheckedexception is thrown. We catch the custom unchecked exception in a catch block and display its error message.
🌐
IBM
public.dhe.ibm.com › software › solutions › curam › 6.0.5.0 › en › html › Developers › CuramWebClientReferenceManual › r_WEBCREF_Conversion1CustomExceptionClasses1.html
Custom Exception Classes
Perhaps one is a generic message ... mechanism is automatic. Figure 4. Throwing Multiple Exceptions · throw new CustomConversionException( -200000, myInvalidValue, new CustomConversionException(-200003));...
🌐
Baeldung
baeldung.com › home › java › core java › create a custom exception in java
Create a Custom Exception in Java | Baeldung
May 11, 2024 - Note that we also have to provide a constructor that takes a String as the error message and called the parent class constructor. This is all we need to do to define a custom exception. Next, let’s see how we can use the custom exception in our example: try (Scanner file = new Scanner(new File(fileName))) { if (file.hasNextLine()) return file.nextLine(); } catch (FileNotFoundException e) { if (!isCorrectFileName(fileName)) { throw new IncorrectFileNameException("Incorrect filename : " + fileName ); } //... }
🌐
Stackify
stackify.com › java-custom-exceptions
Implement Custom Exceptions in Java: Why, When and How
May 1, 2023 - /** * The MyBusinessException wraps all checked standard Java exception and enriches them with a custom error code. * You can use this code to retrieve localized error messages and to link to our online documentation. * * @author TJanssen */ public class MyBusinessException extends Exception { ... } Quite often, your code catches a standard exception before you throw ...
🌐
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 - Let’s create a custom exception that represents a banking overdraft. For example, when a user attempts to withdraw more money from their account than the available balance, this exception will be thrown. In its simplest form, the OverdraftException could look like this: public class OverdraftException extends Exception { public OverdraftException(String message) { super(message); } }
🌐
Rollbar
rollbar.com › home › how to throw exceptions in java
How to Throw Exceptions in Java | Rollbar
2 weeks ago - Let's start with the basics of throwing exceptions then work our way up to when and how to create your own. Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw.
🌐
Vultr Docs
docs.vultr.com › java › examples › create-custom-exception
Java Program to Create custom exception | Vultr Docs
December 16, 2024 - The method declares that it might throw this type of exception by using the throws keyword. Sometimes, you might want to include more context or functionality in your custom exception class.
🌐
Reddit
reddit.com › r/javahelp › help with throwing custom exception (homework)
r/javahelp on Reddit: Help with throwing custom exception (Homework)
January 29, 2021 -

I don't really work with exception handling a lot, so I'm out of my comfort zone for this assignment. In essence, the code I'm testing is a List object, checking it to see if the object I want to add already exists within the list, and throwing a custom exception if it does. I'm using junit testing, if that matters.

public void addConnection(LinkedInUser user) throws LinkedInException
{
	try {
		for (int x = 0; x < connections.size(); x++)
		{
			if (connections.get(x) == user)
				throw new LinkedInException();
		}
		//if (connections.contains(user))
		//	throw new LinkedInException();
		//else
		connections.add(user);
	} catch (LinkedInException e) {
		e.Exception("You are already connected with this user");
	}
}

The commented portion was the old code. I think the problem is determining whether or not the object is already within the list, but I could be wrong. The LinkedInException class is just an empty class. Our instructor told us to override the five Exception class constructors, but that was it, so the overrides are blank.

Here's the junit test code

@Test
public void errorCheckAddCon()
{
	LinkedInUser test = new LinkedInUser("han", "password123");
	LinkedInUser test1 = new LinkedInUser("luke", "password123");
	boolean exceptionThrown = false;
	
	try {
		test.addConnection(test1);
		test.addConnection(test1);
	} catch (LinkedInException e) {
		exceptionThrown = true;
	}
	
	Assert.assertTrue(exceptionThrown);
}

(I think it's the addConnection method, and specifically the List.contains method within, because I manually set boolean exceptionThrown to true, and the junit test passed, so the junit test code isn't the issue here I believe)

Top answer
1 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 2
1
Why do you have a try-catch block in the addConnection method? Like what purpose do you think it serves?
🌐
GeeksforGeeks
geeksforgeeks.org › java › user-defined-custom-exception-in-java
User-Defined Custom Exception in Java - GeeksforGeeks
Explanation: The above example defines a custom unchecked exception DivideByZeroException that is thrown when we are trying to divide by zero. The divide() method checks if the denominator is zero and throws the exception if true. In the main() method, the exception is caught and the error message is printed.
Published   August 14, 2025
🌐
LambdaTest Community
community.lambdatest.com › general discussions
How to Create and Handle a Custom Exception in Java - LambdaTest Community
March 16, 2025 - What is the correct way to create a Java custom exception? I want to define my own exception type and throw it when a specific condition is met. For example, in a try block, I read a string using reader.readLine(), and …
Top answer
1 of 7
16

Like many things in programming, using custom exceptions is good if done for the right reasons and in the right situations.

If a built-in exception can acurrately describe the situation at hand, use it. E.g. FileNotFoundException, TimeoutException, KeyNotFoundException, etc.

If non of the built-in exception classes describe the situation, then you should make your own. If custom exceptions were bad, the built-in classes would be sealed or final or similar. However, don't go nuts. Just like with classes, a given exception type should probably be thrown from more than one place, otherwise it is likely unnecessarily specific.

However, a better rule of the thumb for whether to have custom exceptions is to consider what the caller will do about it when the exception gets thrown. If you have three erroneous situations that are handled in three very different ways, it makes sense to have three types because then the caller can have three catch blocks accordingly. The alternative, which is to inspect the message or data to decide what to do, is more complicated and thus more prone to error.

If all three situations instead are handled identically, it may not be worth the hassle of additional types, when just using the exception message should be enough to diagnose what the situation is. I've had to deal with many situations where a function can throw a dozen different exception types, but that to me as the caller, have inconsequential differences, so laziness kicks in and I just catch {} without the exception type and feel a little guilty about it. Don't cause that to happen.

As for one of the claims you wrote:

catching exceptions is performance hurting.

While that is true, there is virtually no difference between having custom exceptions that are caught and thrown vs just using ApplicationException for everything and making decisions based on the exception message. However, the for former situation, it is considerably easier for us humans to reason about what is happening during program execution.

2 of 7
6

There's one thing I see in the existing answers that bothers me:

Catching custom exceptions might be code smell.

If you are creating custom exceptions, you shouldn't be catching them. Exceptions are for when things go horribly wrong and recovery is impossible. Exceptions that can be handled are either your own fault or vexing.

Taking from the MSDN article Vexing Exceptions:

I first classify every exception I might catch into one of four buckets which I label fatal, boneheaded, vexing and exogenous.

Fatal exceptions are not your fault, you cannot prevent them, and you cannot sensibly clean up from them.

Boneheaded exceptions are your own darn fault, you could have prevented them and therefore they are bugs in your code.

Vexing exceptions are the result of unfortunate design decisions.

And finally, exogenous exceptions appear to be somewhat like vexing exceptions except that they are not the result of unfortunate design choices. Rather, they are the result of untidy external realities impinging upon your beautiful, crisp program logic.

I recommend reading the whole post.

Any design that creates vexing exceptions is a bad design. You (and anyone else writing code against your api) has to catch them, and doing so is vexing: so avoid creating new vexing exceptions.

Custom exception types should either be exogenous ("I'm sorry, Dave, but the database went offline")--and most of these kinds of exceptions have already been written--or Fatal and you should never handle fatal exceptions.

This last point is not adequately presented in the other answers. A bad credit card number is a validation error not an exception. Errors are communicated to the user because they can fix it. Exceptions are things the user can never do anything about. Exogenous exceptions are the exception here, as they are the fault of the world at large and the user needs to be aware of them, even if they can't fix it (but sometimes they can: Internet is disabled, the disk was ejected, the information was wrong. Regardless, there is nothing you as the developer can do to fix it: catch, display, don't crash).

A FamilyNameException is boneheaded: your code had a bug in it. Do not create boneheaded exceptions, do not handle them, write your code correctly in the first place so that these do not occur. Custom exception types are inappropriate for this reason.

A LoginException is either exogenous (the database is offline) or PEBKAC. If it is a PEBKAC error, it isn't an exception. If it is exogenous, why is the existing exception type not sufficient? There may be cases where custom exception types are relevant, but be sure to communicate properly! For example I wrote some code that communicated with an external service, which took time. My coworker was trying to ask my code for the results before the request had time to return, so my code had to generate an exception. However, he took this exception (which was boneheaded in nature) and treated it like a vexing: caught the error and assumed all zeros, thereby introducing a bug: the data retrieved from the external service was wrong! (No, the data was right, but he wasn't displaying the retrieved data and blamed my code). I ended up having to fix his code twice (he removed my first fix about 2 weeks after I added it).

To sum up:

  • Catching any fatal or boneheaded exception is code smell.
  • A custom vexing exception class is code smell. See also: How to avoid vexing exceptions.
  • Be careful with custom exogenous exceptions: they are either redundant or can be mistaken for vexing exceptions.
🌐
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 - However, it is possible for your program to throw an exception explicitly, using the throw statement. The throw keyword is used to explicitly throw a single exception. We specify the exception object which is to be thrown.