How to create a custom exception type in Java?
You should be able to create a custom exception class that extends the Exception
class, for example:
class WordContainsException extends Exception
{
// Parameterless Constructor
public WordContainsException() {}
// Constructor that accepts a message
public WordContainsException(String message)
{
super(message);
}
}
Usage:
try
{
if(word.contains(" "))
{
throw new WordContainsException();
}
}
catch(WordContainsException ex)
{
// Process message however you would like
}
How to create a custom exception which wraps mutliple exceptions in java
In the spirit of the question as asked:
You would have to catch the various exceptions within your method, and then throw a CustomException
from your catch
block. The ability for an exception to "wrap" around another exception is built in via the Exception
class itself (see the Exception(Throwable cause)
constructor).
public void method() throws IOException, CustomException {
try {
//Body of the method
} catch (IllegalArgumentException | InstantiationException | IllegalAccessException e) {
throw new CustomException(e);
}
}
That said, IllegalArgumentException
is not a checked exception, so you wouldn't have to declare it anyway.
Also worth pointing out, the above is based on you specifying that you want to create a custom exception. Another option is to declare in your throws
clause some type that is a common base class of the various checked exceptions that might actually be thrown. For example, both of the checked exceptions in your list are subclasses of ReflectiveOperationException
, so you could just say
public void method() throws IOException, ReflectiveOperationException {
//Body of the method
}
The trade-off, of course, is that you're not being as informative to those writing code that calls your method, so that may limit the quality of their exception handlers. In the extreme, you could just say throws Thorwable
, but this is pretty poor form.
How to create a proper custom exception class?
Exceptions should be used for handling errors, invalid input, illegal, unusual situations. If not guessing the correct number is an error, that sounds like not being a mind reader is an error. So BadGuessException
is misused here.
For a better use case, how about throwing this exception for non-sense input? For example, since the program asks the user to input a number between 1 and 10, inputting -3 or 99 would be clearly an error.
The loop in the middle can be corrected accordingly:
while (!win) {
System.out.println("Guess a number between 1 and 10: ");
try {
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
System.out.println("YOU GOT IT!");
System.out.println("It took you " + numberOfTries + " tires.");
} else if (guess < 1 || guess > 10) {
throw new BadGuessException();
}
} catch (InputMismatchException e) {
input.nextLine();
}
}
As for creating a custom exception class, you already did that. It's written a bit messy way, cleaning it up (removing unnecessary stuff) it becomes:
public class BadGuessException extends Exception {
private static final String message = "Sorry, that was an invalid guess!";
public BadGuessException() {
super(message);
}
}
UPDATE
I fixed another bug in your code: if you enter non-integer input, a InputMismatchException
will be thrown. Repeatedly. Forever.
This is because the input.nextInt()
doesn't consume the input if it's not valid. So the invalid input stays there, and input.nextInt()
will keep failing, putting your program in an infinite loop.
To fix that, you must consume the bad input somehow, for example by reading the line:
} catch (InputMismatchException e) {
input.nextLine();
}
How can I write custom Exceptions?
All you need to do is create a new class
and have it extend Exception
.
If you want an Exception
that is unchecked, you need to extend RuntimeException
.
Note: A checked Exception
is one that requires you to either surround the Exception
in a try
/catch
block or have a 'throws
' clause on the method declaration. (like IOException
) Unchecked Exceptions
may be thrown just like checked Exceptions
, but you aren't required to explicitly handle them in any way (IndexOutOfBoundsException
).
For example:
public class MyNewException extends RuntimeException {
public MyNewException(){
super();
}
public MyNewException(String message){
super(message);
}
}
Creating custom exception in java in a single class is bad practice?
Best practice is to have the custom exceptions classes outside the main code, better in separate files
public class Test {
static String s1, s2 = null;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter diection of first vehicle");
s1 = sc.nextLine();
System.out.println("enter direction of second vehicle");
s2 = sc.nextLine();
try {
if (s1.equals(s2)) {
System.out.println("everything is fine no exception");
} else {
if (s1.equals("FOO")) {
throw new IncorrectWord("Foo is an incorrect word");
} else {
throw new Collision();
}
}
} catch (Collision | IncorrectWord e) {
System.out.println("this is a exception ");
}
sc.close();
}
}
Errors, put it in separate files
class Collision extends Exception {
}
class IncorrectWord extends Exception {
public IncorrectWord(String errorMessage) {
super(errorMessage);
}
}
Custom Exception-Java
Your question was a little confusive but I guess you want to create a new exception.
Create a file MyAppException.java
class MyAppException extends Exception {
private String message = null;
public MyAppException() {
super();
}
public MyAppException(String message) {
super(message);
this.message = message;
}
}
You can throw it via
throw new MyAppException();
But I guess an exception is not needed for what you want:
public static String readId() {
String id = "";
while(true){
id = leer.next();
try{
Integer.parseInt(id.substring(0,8));
}catch(InputMismatchException e){
System.out.println("Invalid Input");
continue;
}
if(id.length() != 9)continue;
if(Character.isLetter(id.chatAt(8)))break;
}
return id;
}
Related Topics
Meaning of Delta or Epsilon Argument of Assertequals for Double Values
How to Bind an Object List with Thymeleaf
Output an Image File from a Servlet
What's the Difference Between Instance Method Reference Types in Java 8
How to Write a Compareto Method Which Compares Objects
What Is Inside Com.Sun Package
Jackson Overcoming Underscores in Favor of Camel-Case
How to Generate Javadoc HTML Files in Eclipse
Java 7 String - Substring Complexity
Modifying Local Variable from Inside Lambda
Pass a Local File in to Url in Java
How to Get a Spring Bean in a Servlet Filter
Stopping a Window from Displaying Till It Is Fully Drawn
Using Javafx in Jre 8, "Access Restriction" Error
Dealing with Randomly Generated and Inconsistent JSON Field/Key Names Using Gson