Using throw for user defined exception - java

Following is the code where " throw use; " shows an error.Why? How to use throw for user defined exceptions?Give some example?
class use extends Exception{
public String toString() {
return "too many exceptions";
}
}
class user{
public static void main(String s[]) {
int i=3;
try {
if(i>1)
throw use;
}
catch(use e) {
System.out.println(e.toString());
}
finally{
System.out.println("program executed successfully!");
}
}
}

you need an instance of the exception class to throw it:
throw new use();
or
use a = new use();
throw a;
In the future please follow Java naming conventions, it will make your code much more readable. (class names should start with a capital letter).

User defined exceptions can be created and thrown in Java.
By inheriting the Exception class you can create your own exceptions.
And it can be thrown as and when required
Following example shows how to create and throw user defined exceptions
http://www.csnotes32.com/2014/09/how-to-create-user-defined-exception-in.html

And remember, you don't need to roll your own.
throw new RuntimeException("Do not instantiate this class");
(old question, but I always forget syntax, so stashing on google)

Related

Can I define multiple custom exceptions in java in a single class file and invoke them via methods?

I'm trying to get into exception handling via custom exceptions.
I'm creating the class CustomExceptions and extending Exception as follows:
public class CustomExceptions extends Exception{
public CustomExceptions (String s) {
super(s);
}
However, rather than having to create multiple files for every custom exception I want, or bloating my main class file, I'd like to put all of my custom exceptions in this class and invoke them via a method
So let's say that I want to handle 2 situations: When the user tries to input a seat reservation, but the seat is already taken, and when the user tries to provide a ticket for someone outside of the age range.
Can I create 2 methods inside of the CustomExceptions class which invoke the constructor passing a custom message to it?
public void seatTaken(String s) {
String s = "The seat is taken, please choose a new one";
CustomExceptions(s);
}
public void notOldEnough(String s) {
String s = "User is not old enough for this movie.";
CustomExceptions(s)
}
}
Would this work? Or am I forced to create multiple custom exception files?
Generally custom exceptions should be defined in the top level. Because, almost universally, these exceptions are part of the interface of the package or module.
If the user cannot see them, then how are they going to catch them separately? And if you don't want to catch them separately, then why would you need separate classes?
However, if you must, you can include them into a class for which they are required:
public class SeatReservationSystem {
public static class ReservationFailedException {
... constructors taking a message ...
}
public static class SeatTakenException extends ReservationFailedException {
... constructors taking a message ...
}
public static class OutsideAgeException extends ReservationFailedException {
... constructors taking a message ...
}
....
}
After that you can create any method that returns them as required. Don't create methods that throw them as the compiler won't see those as exit points of the block you're in, and you'll get strange situations.
Here is some code to show what I mean:
// wrong
public static void throwRuntimeException() throws RuntimeException {
throw new RuntimeException();
}
// correct, but dangerous
public static RuntimeException createRuntimeException() {
return new RuntimeException();
}
public static void main(String[] args) {
String initializeMeOrThrowException;
if (new Random().nextBoolean()) {
// compiler doesn't recognize that the method always throws an exception
throwRuntimeException();
// this the compiler can understand, there is an explicit throw here:
// throw createRuntimeException();
// but this is the pitfall, it doesn't do anything:
// createRuntimeException();
} else {
initializeMeOrThrowException = "Initialized!";
}
// Compiler error for throwRuntimeException and createRuntimeException without throws:
// "The local variable initializeMeOrThrowException may not have been initialized"
System.out.println(initializeMeOrThrowException);
}
However, experience learns me that I forget the throws statement for the throw createException(...); method, and the stupid compiler doesn't warn me about that (even though the statement is utterly useless without it). So I try and not use either.
Note that I'm not certain if you should use exceptions for this. If your system is a reservation system, then refusing tickets is not that exceptional. Returning a ReservationResult makes more sense.

Exception flow control

I use exceptions to flow control a lot, but I have a strange feeling that I am doing something wrong. Is it a good practice to write something like code shown bellow?
public static void main(String[] args)
{
try
{
methodA();
}
catch (Exception ex)
{
handleException(ex);
}
}
public static methodA()
{
methodB();
}
public static methodB()
{
if(someConditionIsNotMet)
{
throw new RuntimeException("Some Condition Is Not Met");
}
}
I use exceptions to flow control a lot
Throwing specific and functional exceptions to indicate a functional issue during the workflow is not bad itself.
It is not the single way to do it but it is a valid way.
Another way relies on methods that returns boolean and testing the returned value.
Personally, I don't use this way as I found it rather verbose, error-prone (we have not to forget to test the returned boolean) and less expressive (it has only two values: true and false) than an exception (it may have as many as required).
Suppose that method B has to check something and that if the check fails the processing should be stopped and the client notified of the issue, it would be totally valid to use exceptions for this purpose.
Now, it would make more sense to make the exception a specific exception rather than Exception.
Otherwise how the client could interpret the exception meaning ?
The exception could be a workflow exception but it could be also any exception thrown at runtime for another reason such as a NullPointerException.
You want to handle workflow exceptions in a specific way while you will not apply a specific processing to other thrown exceptions.
For example you could write something as :
public static methodA()
{
methodB();
}
public static methodB(){
if (!expectedDataFound()){
throw new DataNotFoundException("data xxx was not found");
}
if (!hasRights()){
throw new PermissionException("user xxx has not the rights for yyy");
}
}
Then from the client side, you have two ways.
Catching each exception individually or catching them in a common way (that is possible only if they make part of the same hierarchy).
Catching each exception individually :
public static void main(String[] args)
{
try
{
methodA();
}
catch (DataNotFoundException ex)
{
handleDataNotFoundException(ex);
}
catch (PermissionException ex)
{
handlePermissionException(ex);
}
}
Catching exception globally:
public static void main(String[] args)
{
try
{
methodA();
}
catch (WorkflowException ex)
{
handleWorkflowException(ex);
}
}
I think you are too harsh on yourself with saying that you "use exceptions to control flow". It is an antipattern to use exceptions for control flow, but in your example you do not.
Let's say that you have a method that sets the age for the user, and of course if the caller provided negative number, you should not complete the action. So a very reasonable way to ensure that, would be:
public void setAge(int age) {
if(age <0) {
throw new InvalidArgumentException("Age has to be zero or positive number");
}
}
If you prefer not to use exceptions maybe you can use features of the language such as Optionals or create response structure that handles both success and errors. For example, lets say you have a method that retrieves employees
public EmployeesOverview getEmployees() { ... }
Your response class could look like this:
public class EmployeesOverview {
private Ok ok;
private Error error;
class Ok {
private Set<Employee> employees;
}
class Error {
private String errorMessage;
}
}
So without throwing exception your method will provide clients with results or if there is a problem, the client will be informed about it.
I would separate flow control and exception handling. Flow control is meant for making sure statements are executed in correct sequence and under correct conditions. This must be determined at design time. Exception handling is meant to handle unforeseen situations at run time. Exceptions are almost always due to external factors: time outs, no disk space, data errors...
Just my two cents.

java exception catching in a different class than throwing

I have been working on a code that does 2 things:
Has a class that performs computations (logic)
has a class that displays the result.
I am wondering if it is possible to use try/catch statements in the Display class, where I would attempt to catch exceptions originating in the logic class.
Where Display would execute a line similar to logic.execute(input);
I was able to create a custom exception class where the following is placed in display class:
try{
logic.execute(input);
}catch(CustomException e){
//print statements
}
However I would like to be able to print exactly the error that occured, such as NullPointerException.
When i say print, i mean output in console. (but it must originate from display class)
If such a monstrosity is possible, please let me know.
Thank You guys!
Yes, it's possible.
You will need your custom exception class to extend RuntimeException instead of Exception, or the compiler will complain that you are not catching the exception that you throw.
See this post: Throwing custom exceptions in Java
Simple working example:
public class ExceptionTest
{
public static void main(String[] args)
{
SomeClass myObject = new SomeClass();
myObject.testFunction();
}
}
public class SomeClass
{
private SomeOtherClass someOther = new SomeOtherClass();
public void testFunction()
{
try{
someOther.someOtherFunction();
}
catch(Exception e){
System.out.println(e.toString());
}
}
}
public class SomeOtherClass
{
public void someOtherFunction()
{
throw new CustomException("This is a custom exception!");
}
}
public class CustomException extends RuntimeException
{
public CustomException(String message)
{
super(message);
}
}

why cant custom Exception be caught in generic catch clause

Please examine my custom exception below:
public class ReportException extends Exception {
private int mCode = -1;
private String mString = "";
public ReportException(int code, String description)
{
super(description);
mCode = code;
mString = description;
}
public int getCode()
{
return mCode;
}
public String getString()
{
return mString;
}
}
My question is why is this illegal in another class:
try{
throw new NullPointerException();
}
catch(ReportException e){
}
To me a NullPointerException is derived from Exception class and so is my custom ReportException so since there the same type i'd expect it can be caught in the catch clause. But my IDE says this is illegal. I had this discussion with a colleague of mine and he said there it cant be done but im just wondering why since they both derive from the same Exception class. This looks to defy polymorphism.
A NullPointerException and your ReportException are both Exceptions, but to catch a ReportException, you must throw a ReportException (or a subclass). A NullPointerException is not a subclass of ReportException, so it's not caught.
Throw a ReportException instead.
Some code inside the try block has to throw your checked exception before you can explicitly catch it.
This is valid:
try {
throw new ReportException();
}
catch(ReportException e){
// handle it
}
See Java: checked vs unchecked exception explanation
Every single class in java is a successor of java.lang.Object, but that doesn't mean that all of these classes are cast-able to each-other.
To a computer those two classes are completely different to each-other.

High Level Overview Of Throwing Exceptions In Java

I am a little bit confused with exceptions in Java and when to use which particular style of implementation.
I used IllegalArgumentException as an example, but the main point I would like to address is when does one throw, extends or throw new exception?
Also as an additional point I have an assignment where I have to create a java class and the spec vaguely states that the constructor should throw an IllegalArgumentException so which one would be the best to use?
public class Test{
//when does one use this type of exception
public Test(String yourName) throws IllegalArgumentException{
//code implemented
}
//when does one use this type of exception
public Test(String yourName) extends IllegalArgumentException{
//code implemented
}
public Test(String yourName){
if(yourName.length() <= 0){
//why not use this type of exception instead
//and what happens when I use this type of exception
throw new IllegalArgumentException("Please Enter Your Name..!");
}
}
}
Thanks in advance.
When some Exception occurs, you have two ways of handling it: doing throws from the method or doing try-catch. The first one looks like this:
public class MyClass {
public void myMethod() throws IllegalArgumentException {
someOtherMethod();
}
}
In this case you know that someOtherMethod() can throw an exception and you don't want to handle it - you just pass it further. After that, the invoker of myMethod() should take care of the Exception.
But the second way is when you handle it by yourself:
public void myMethod() {
try {
someOtherMethod();
} catch (Exception e) {
System.out.println("You've got an exception!");
}
}
About throwing exceptions manually - you may suppose that you do it in someOtherMethod(). When you do throw new IllegalArgumentException("Please Enter Your Name..!"); the program stops with a message about this exception (unless you handle it in a try-catch way).
And at last, you extend some exception, when you create your own Exception class:
class MyException extends IllegalArgumentException {
...
}
In this case you may do throw new MyException(); in your code.
I'd advise you to read more about exceptions in Java to understand what is going on. You may start with this lesson.
To ensure that you don't end up creating exceptions which already have equivalent in the standard library, I normally have a peek at the documentation before creating new exceptions. Also, it's very easy to go crazy with really big exception hierarchies if you are not careful. Don't create new exceptions just because you think you need to throw one somehow; create one because a code somewhere down the call stack would be doing something useful/different with that exception.
public Test(String yourName) throws IllegalArgumentException
You normally never specify runtime exception in the throws clause though it might be helpful if you need this information to be part of the public API.
public Test(String yourName) extends IllegalArgumentException
This doesn't look right and isn't valid Java.
I would only create a new exception type when you need to. You need a new type when you expect the caller to have catch clause for your new exception.
you can create new exceptions just to be more descriptive but that is what I use the message for.

Categories

Resources