-2

I know Exception handling in Java a little bit. I am not getting when one should write the code which will explicitly throw an exception. Any practical scenario with code will be helpful.

Zubin Shah
  • 370
  • 2
  • 4
  • this is not a question for here. it's just for someone that doesn't want the code to proceed and want to track down where and why the process failed – No Idea For Name Aug 06 '13 at 12:35
  • possible duplicate of [When to throw an exception](http://stackoverflow.com/questions/77127/when-to-throw-an-exception) – No Idea For Name Aug 06 '13 at 12:36
  • You do know that every exception included in the Java framework was coded by the guys at Sun and then Oracle, right? They didn't just pop out of the void. So just analyse the circumnstances in which each exception is naturally thrown by Java. Study their motives. That might open your mind. – Geeky Guy Aug 06 '13 at 12:38

4 Answers4

3

let say you have a pricing application . In some class you have method calculateCommision()

 public Double calculateCommision(Double price){

    if(price<0)
       throw new RuntimeException("Negative price ");
     -------
     // Some calculations
  }

Which indicates price could not be negative. which is helpfull message .

amicngh
  • 7,831
  • 3
  • 35
  • 54
2

Example from JDK

public File(String pathname) {
    if (pathname == null) {
        throw new NullPointerException();
    }
    ...
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1
class MyClass{

    void doSomething(MyObject o){
        if(o.myParameter == badValue){
            throw new myException();
        }
    }
}

See here for a longer explanation of when to throw an exception.

Community
  • 1
  • 1
q99
  • 961
  • 2
  • 13
  • 27
1

Exceptions should not be meant to use as a test case to execute different scenarios. You can read more information from here http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html

But still If you have a DB entry where you can have a number and a string where you want to distinguish between those two, you can handle the string as a number (Integer.parseInt()), and it will throw a NumberFormatException(). Then you can handle it as a string. But best practice is not to use it that way. Just to handle it and log it, so you can fix the source code.

dinesh707
  • 12,106
  • 22
  • 84
  • 134