Try block without a catch block

Hai!
I heared that java developers to make the java a familiear one used the syntax like c++. But i am surprised after seeing that
in java a try block is allowed with out a catch block if it has a finally block
1) i can't imagine such a situation. What is the use in doing so
2) Why java developers sacrificed the familierity in this issue.
clarify me.
Bye

in java a try block is allowed with out a catch block
if it has a finally block
1) i can't imagine such a situation. What is the use
in doing soWhen you want to do cleanup on the way out, regardless of whether the try block completes normally (executes its last statement) or abrubtly (return, exception thrown, break, continue).
2) Why java developers sacrificed the familierity in
this issue.I didn't sacrifce any familiarity. Keeping something the same as C++ for reasons of "familiarity" would be stupid. If it's just going to be the same as C++, why make a new laguage? You keep or don't keep features based on your assessment of their value in achieving the goals that you've set for your language. "Familiarity" was not likely an important goal for the creators of Java, and I'm glad for that.

Similar Messages

  • Txt file read in- StringTokenizer- Try Block Catch for errors

    Hello
    So I am having a few issues with a school project. First is with my ReadWithScanner. It does not read in the file giving me a NullPointerException error on the line <Scanner in = new>. I have tried a few other read in files and they do not seem to be working.
    I am also stuck on the logic on the try block catch statement. How does a person set up a �custom� try block that looks for errors like the ones below? I have attempted to start in the commented code.
    The text file has to read in 1000 individual lines of code and are separated by �;� and should be separated into tokens with the StringTokenizer class what I attempted to do below also. Both are mere attempts and need help�
    This is some what of the logic I thought of doing
    1.Read the first line in first with the scanner class
    2.use delimiter separated by �;�
    3.Tokenizer the line into separate tokens- invoiceCode, fName, lName�
    4.Check classes- check Name, check Date, checkPrice, checkPrice, checkGenre, checkShippingDate invoiceCode = "Error Code" checkInvoiceCode(String invoiceCode)checkName(String name), checkPrice(String price), checkGenre(String genre)
    5.Apply the regular expressions to each try block statement
    a.Assign a letter to each error for example if invoice was to short it would be assigned a letter A
    b.If invoice does have the right characters it would be assigned B
    c.If name has to few words it would be assigned D
    d.�
    This is an example of a good field from the text file
    XYG726;Smith,Mr. John M.;29.96;comedy;101008;100604
    Not so good line
    Lu15;Will, Mark;50.00;Science;030305;030807
    The file should then be printed out in the program not to a text file. It only needs to print the invoice number and error code letter assignment.
    If you have any questions feel free to let me know. Thanks for all or any help you have to offer.
    Invoice
    Three upper case letters followed by three digits
    Regular Expression "[A-Z]{3}[0-9]{3}"
    Customer Name
    Should be in the form: last name followed by a <,> optional title (Mrs. Mrs�) then first name optional middle initial Titles must be
    So regular expression something like �[a-z][A-Z]+([A-Z]{1}?[a-z][./})+[a-z][A-Z]�
    Sale Price
    Two decimal digits to the left of the decimal point. The price should not have a leading zero.
    Regular Expression [0-9]{2}*./[0-9]
    Genre
    The genre should only contain lowercase letters. Regular expression �[a-z]�
    ShipDate and Order Date-
    Must be standard dates- MMDDYY. The order date and shipping date has to be after today�s date. Regular expression �[0-9]{2}+[0-9]{2}+[0-9]{2}�
    package Project3;
    import java.util.StringTokenizer;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.io.*;
    import java.util.Scanner;
    public class ReadWithScanner {
    private final File fFile;
    public static void main (String args[]){
    Scanner in = new Scanner(new File("e:\\work_space_java\\Project\\Package3\\movie.txt"));
    Scanner.processLineByLine();
    public ReadWithScanner(String aFileName){
    fFile = new File(aFileName);
    public final void processLineByLine(){
    try {
    //use a Scanner to get each line
    Scanner scanner = new Scanner(fFile);
    while ( scanner.hasNextLine() ){
    processLine( scanner.nextLine() );
    scanner.close();
    catch (IOException ex){
    protected void processLine(String aLine){
    //use a second scanner again to raed the content of each line
    Scanner scanner = new Scanner(aLine);
    scanner.useDelimiter(";");
    if (scanner.hasNext() ){
    //read each file?
    String name = scanner.next();
    String value = scanner.next();
    else {
    scanner.close();
    //Token Names that are seperated
    StringTokenizer st;
    String invoiceCode = st.nextToken();
    String fname = st.nextToken();
    String lname = st.nextToken();
    String price = st.nextToken();
    String genre = st.nextToken();
    String orderDate = st.nextToken();
    String shipDate = st.nextToken();
    String invoiceCode;
    invoiceCode = "A" checkInvoiceCode(String invoiceCode);
    Pattern p = Pattern.compile("[a-z]{6}[A-Z]{6}[0-9]{6}");
    Matcher m = p.matcher(invoiceCode);
    p.matcher(invoiceCode);
    if(m.matches()) {
    System.out.println(invoiceCode);
    else {
    System.out.println ("A");
    try
    invoiceCode = Integer.parseInt(String);
    catch (NumberFormatException e)
    { System.out.println ("B"); System.exit(1); }
    */

    I have made a quite a few updates to my code. Please look it over again. I have also made many comments to help with the logic. Once again if you have any questions please feel free to ask. Sorry about not using the tags before- I was no aware of them. Thanks for the advice sabre150.
    package Project3;
    import java.util.StringTokenizer;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.io.*;
    import java.util.Scanner;
    public class ReadWithScanner {
         private final File fFile;
         public static void main (String args[]){
                   //read in text file from directory currently it can not read the file
                  Scanner in = new Scanner(new File("e:\\work_space_java\\Project\\Package3\\movie.txt"));
                  //Scans each line of the text in
                  Scanner.processLineByLine();
                //assigns new file name to file
                public ReadWithScanner(String aFileName){
                  fFile = new File(aFileName); 
                public final void processLineByLine(){
                  try {
                    //use a Scanner to get each line from the processLineByLine
                    Scanner scanner = new Scanner(fFile);
                    while ( scanner.hasNextLine() ){
                      processLine( scanner.nextLine() );
                    scanner.close();
                  catch (IOException ex){
                protected void processLine(String aLine){
                  //use a second scanner again to read the content of each line
                   //delmiter should then break each line in the text file into seperate "tokens"
                  Scanner scanner = new Scanner(aLine);
                  scanner.useDelimiter(";");
                  if (scanner.hasNext() ){
                       //reads each line from scanner
                    String name = scanner.next();
                  else {
                  scanner.close();
               /*Convert Tokens from Scanner into String Tokenizer with assigment to each variable
                * I am missing something
                * Need to convert each line read from the scanner (name variable) to the String
                * Tokenizer class
              //Tokens names now assigned a varaible
              StringTokenizer st;
              String invoice = st.nextToken();
              String name = st.nextToken();
              String price  = st.nextToken();
              String genre = st.nextToken();
              String orderDate = st.nextToken();
              String shipDate = st.nextToken();
          /*If statments (Try Block Statements?) with Regular Expressions
          * This is where I have the most issues on how to set up
          * "custom" try and block errors trying to match what I have
          * in the regular expressions. 
          * I believe try and catch statements
          * make this easier but I have used 'match' and 'pattern' with if
          * statments.  If try block statements are easier please show!
          * Regular Expressions may not be correct either
           invoice = checkInvoiceCode(invoice);
           //Defined cerita for Inovice are:
           //Error A = Invoice code is too short  
           //Error B = Invoice code does not have the right characters 
           //Error C = Invoice code digits are all zero
           //Checks for error A
           //Has at least six characters
            Pattern invoiceShort = Pattern.compile("{6}");
            Matcher shortInvoice = invoiceShort.matcher(invoice);
            p.matcher(invoiceCode);
            if(m.matches()) {
                 System.out.println(invoice);      
            else {
                 System.out.println ("A");
            //Checks for error B
            //3 Upper Case Letters followed by three numbers,
            Pattern rightChar = Pattern.compile("[A-Z]{3}[0-9]^0{3}");
            Matcher charRight = rightChar.matcher(invoice);
            p.matcher(invoiceCode);
            if(m.matches()) {
                 System.out.println(invoice);
            else {
                     System.out.println ("B");
            //Checks for error C
            //Where the last three digits are not all zeros
            Pattern notZero = Pattern.compile("*{3}^0{3}");
            Matcher ZeroNot = notZero.matcher(invoice);
            p.matcher(invoiceCode);
            if(m.matches()) {
                 System.out.println(invoice); 
                 else {
                     System.out.println ("C");
         //name = checkFullName(name);
         //Error D = Name field has fewer than two words
         //Error E = Name field has more than four words
         //Error F = Name field has no comma
         //Error G = Name field has a bad title 
         //Error H = Name field has a bad initial 
        /*Have a lot more to do...
        * Still need to go through the same if statement or Try Block statements with this data:
        *      String fname = st.nextToken();
              String lname = st.nextToken();
              String price  = st.nextToken();
              String genre = st.nextToken();
              String orderDate = st.nextToken();
              String shipDate = st.nextToken();
        * But for now I would like to see an example of an if statement I could use
        * (if mine is even right) or catch statement- the rest of the project we look
        * for similar certia as defined in the reg exp for invoice
         /*Writes to Report in the Console
         * Prints data into two columns:
         * Invoice Code and Error Type
         //Prints both column Headings
         private void columnHeadings ()
         System.out.println (padL("",5) +
         padL("Invoice",20) +padL("",20)+
         padL("Error Code",40));
         //movie is the name of the text file
         private void printMovie(Movie aReport) {
         System.out.println(aReport.getInvoiceCode()+"\t"+
               aReport.getErrorType()+"\t");
      *This method pads the string start to the length newLength leaving the
      *string left justified and returning the result.
      private String padL (String start, int newLength)
         String result = new String (start);
         while (result.length() <= newLength) result += " ";
         return result;
      } // end padL
       * This method pads the string start to the length newLength leaving the
       * string right justified and returning the result.
      private String padR (String start, int newLength)
         String result = new String (start);
         while (result.length() <= newLength) result = " " + result;
         return result;
    // end padRThanks a lot.

  • Is it possible to get back to the Try block from a Catch block?

    I would like to perform validations on a config file. To do so, I have a method which will throw a MissingConfigException or an InvalidConfigException if something is missing or if something doesn't match a regex pattern. Although I have to do that with many different configs and I would like to go through all of them so that my error message will report all missing / incorrect configs at once instead of 1 at a time. Thus, I wanted to know if there would be any way I could do something like:
    try {
         config.validate("ServerPort","\\d+");
         config.validate("MaxClients","\\d+");
    } catch(MissingConfigException e) {
    } catch(InvalidConfigException e) {
    and have the catch block executed before going through the try block from where the exception was thrown.
    Thanks in advance!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    No, you can't jump back into the try. You can put your try/catch inside a loop though, so that if one fails, it will loop around and start a new try for the next one. Define a class that holds all the data you need to pass to validate, and make an array or List of those objects. Change or add a validate signature that takes this object, or just extract the strings from each one when you call validate.
    ThingToValidate[] val = new ThingToValidate[] { new ThingToValidate("ServerPort", "\\d+"),
        new ThingToValidate("MaxClients", "\\d+"),
    for (int ix = 0; ix < val.length; ix++) {
        try {
            config.validate(val[ix]);
            // OR
            config.validate(val[ix].getThingy, val[ix].getOtherThingy[]);
        catch (....) {
            // logger.warn("failed...");

  • Handling socket exception - Retrying a "try" block

    I have a program which attempts to retrieve an object through a socket. However sometimes I get the following exception:
    java.net.SocketException: Connection reset
    This is a problem as I need the object to continue program execution.
    An overview of the code is:
    try {
                UrlServerObject crawlUrlObj = getUrlToCrawl();
                // Download webpage at the url returned by getUrlToCrawl()
                webpage = loadPage(crawlUrlObj);
    catch(java.net.SocketException ex) {
              System.err.println("An exception occurred.\n" +
                        "The exception was: " + ex.toString());
            }The getUrlToCrawl() method simply opens a socket a communicates with a server which sends back an object.
    My question is what is the best way to catch the exception and "retry" the complete "try" block until an object is read?
    Thanks

    When you say a loop, do you mean something along the
    lines of:
    boolean gotUrl = false;
    while(!gotUrl) {
    UrlServerObject crawlUrlObj = getUrlToCrawl();
    if(crawlUrlObj != null) gotUrl = true;
    }The exception would be thrown in the catch block
    still though?getUrlToCrawl is presumably the code you originally posted? Yep, that's about the size of it. Although I wouldn't keep trying until you got a URL, you should consider the possibility that there isn't one, and deal with that. I'd try it a set number of times, and move on after that

  • Return statement inside try block

    what is wrong if i write code like as below...please explain me since i am new to java
    class sample{
    public String method(){
    try{
    String str="abc";
    return abc;
    catch(Exception e){}
    }

    veldhanas wrote:
    return abc;In your code there is no varible declared as abc. It is a value assigned in str.
    Suppose if the code in try statement throws exception the return statement is skipped and the
    associated catch block will get executed. So your catch block must return a result of type String.... or throw another (or the same) exception.
    In this case, since there's no way the code in the given "try" block can throw an exception, it would have been better to not even have a try/catch block in the first place.
    And almost never just swallow exceptions like that (an empty catch block). There are only a few cases where it's ok to swallow them (such as in finally blocks where you're cleaning up resources which may throw exceptions while cleaning up, and you want to continue cleaning up and ignore those kinds of exceptions).

  • Won't recognise code in try block

    I've got a try block which has a line of code in it as shown:
         public static String ProcessUserInput(){          
              BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
              try{
         String line = kbd.readLine();
    catch (IOException ex)
    System.out.println( "Error reading keyboard input." );
    return line;
    When i compile this it gives me this error:
    cannot resolve symbol
    symbol : variable line
    location: class UserException
    return line;
    It seem like it does not recognise what is in the try block why is this.

    A variable's scope--the piece of your code where it's visible--is the nearest enclosing block. In this case, line is only visible in the try block.
    String line = null;
    try {
        line = kbe.readLine();
    catch (...) {
    return line;Side note: Just printing an error message is NOT the way to handle exceptions. First, it lets subsequent code continue executing as if everything's fine--you've taken away its way of knowing that things are NOT fine. You should either actually handle the exception (by providing some default behavior, or retrying), or else just let it be thrown, or wrap it and rethrow it.

  • Try block inside a try block - who is throwing StaleConnectionException?

    int retry = 0;
    try{ //MAIN TRY
    //GET Datasource from context<---is this throwing?
    boolean retry = false;
    do {
         try {
              retry = false;
    GET CONNECTION FROM DATASOURCE<--or shld this be?
         }catch(SQLException e) {
         //FIRST CATCH
         if (retryattempts++ < 3){
              retry = true;
    } while (retry);
    //DO something which requires try block
    }catch(SQLException e)
    {//Second catch
    When I do this the StaleConnectionException is caught by the second catch... does this mean that the staleconnectionexception is thrown when getting datasource from initialcontext and not while getting connections?
    Edited by: wannaBeACsGrad on Jan 10, 2008 9:09 AM

    I am not sure what your are trying to do. Your code as posted is incomplete and could not possibly compile. The Try/catches do not seem to be nested.
    More importantly, why in the world would you ever want to have a try inside a try? You can have a single try, then several different calls in loops or whatever that can potentially throw Exceptions and then have mulitple catch statements to handle them. For instance, you could have something like this:
    try {
    } catch (NullPointerException ne) {
       // handle null issues here
    } catch (NumberFormatException nfe) {
       // handle number format issues here
    } catch (Exception e) {
       // everything else falls here
    }Keep in mind that you don't want to do any "Error Hiding". Make sure you handle each case appropriately.

  • Can't throw exception inside try block!

    Hi,
    I'm having a problem trying to throw an error inside a try block.
    To illustrate:
    public class TestException {
    public TestException() {
    try {
    int ret = foo();
    System.out.println("ret is " + ret);
    } catch (Exception ex) {
    System.out.println("exception caught");
    public int foo() throws Exception {
    int ret = 0;
    try {
    throw new Exception("test exception");
    } finally {
    return ret;
    public static void main(String[] args) {
    new TestException();
    If I run this the only output is "ret is 0" - I do not catch the thrown exception! What am I doing wrong?
    Any and all help will be very gratefully received.
    Thanks.

    I need to correct myself: I've re-read the spec, and actually the behaviour is conformant with the JLS: JLS says that the return statement completes abruptly, and an abrupt return in a finally block that didn't have a (applicable or any) catch block will result in the original exception being 'forgotten'.
    Very unintuitive, but as-spec'ed

  • While local variable initialized inside try block compiler throws error???

    Check out this code where two local variables(one String and the other int type) is declared at the beginning of the method and initialized inside try block. now when i compile this app, it gives an error sayin' that Variables not been initialized. Can anyone tell me why compiler is throwin' an error message?
    Many thanks.
    import java.io.*;
    public class Test{
    public static void main(String[] args){
    String aa;
    int c;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("EnterAnything:");
    try{
    aa = in.readLine();
    c = 1;
    catch(IOException e){
    System.out.println(e.getMessage());
    System.out.println(aa);
    System.out.println(c);
    }

    jfbriere,
    Thanks to u all.
    that every reference to the variable is necessarily preceded
    by execution of an assignment
    to the variable.But I've initialized the variable c and aa inside try block before referencing it as a parameter of println()?
    Can u clarify this?
    --DM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Posiibility for terminating jvm inside try block so that finally block wont

    posiibility for terminating jvm inside try block so that finally block wont execute at all ?
    But in that case what will happen?
    Is it safe for any practical situation ?
    Threads: t.stop()
    JVM : System.exit()
    which one can really help and where?

    What if security Manager comes into picture?
    class ExitCatchingSecurityManager extends SecurityManager
    public void checkExit(int status)
    Process.terminateProcessWithThreadGroup(getThreadGroup());
    throw new SecurityException();
    What if an application calls System.exit()?
    We still have one big hole in our multiprocess library. If any application calls System.exit(), the JVM terminates, and all the pseudo-processes will be destroyed with no warning. Fortunately, Java's design once again comes to our aid. Any call to System.exit() is first checked by the SecurityManager to see if the application has permission to terminate the JVM. We can install our own SecurityManager to catch the System.exit() call, disallow it, and terminate the pseudo-process instead. The SecurityManager is actually quite simple to define:
    class ExitCatchingSecurityManager extends SecurityManager
    public void checkExit(int status)
    Process.terminateProcessWithThreadGroup(getThreadGroup());
    throw new SecurityException();
    In addition, the SecurityManager should define all other checks so that they do not block pseudo-processes from running. A simple null call for all check* methods will work. We install our own SecurityManager by calling System.setSecurityManager(), i.e., by adding the following line near the startup of the multiprocess library:
    System.setSecurityManager(new ExitCatchingSecurityManager());
    The Process.terminateProcessWithThreadGroup() method is simple to define, by holding a collection of Process objects in the Process class, searching the collection to find the Process with the identical ThreadGroup, then terminating that Process.

  • Try block problem !

    Hi all,
    I have problem to compile java program which has a large block of try {}
    This is the error message
    C:\Program Files\crt_table.java:3011: code too large for try statement
    catch (Exception e)
    ^
    anyone has solution to this type of problem ?
    Thanks in advance.

    How many different types of exception are you trying to catch ?
    Surely, if the try block is so big that the compiler is objecting, then you should be able to break the block down into smaller try blocks each of which is just catching one or two different exceptions. And perhaps you have code in this block which couldn't possibly cause an exception and doesn't need to be in a try block ?

  • Parameters in try block..pls help

    I have the following code which I do not understand the reason it is not work. i.e. Putting the driver, dbURL, login, password value in the beginning work, however, setting it in the try blocks does not. Can you please help me? Thank you.
    public ConnectionManager()
    // (This block works OK if uncommented)
    //driver = "com.mysql.jdbc.Driver";
    //dbURL = "jdbc:mysql://localhost/BOOKINGSYSTEM";
    //login = "root";
    //password = "password";
    try {
    Properties Prop = new Properties();
    InputStream configStream = ConnectionManager.class.getClass().getResourceAsStream("/config/database.properties");
    Prop.load(configStream);
    configStream.close();
    //driver =Prop.getProperty("driver");
    //dbURL = Prop.getProperty("dbURL");
    //login = Prop.getProperty("login");
    //password = Prop.getProperty("password");
    // (This block DOES NOT works...why??)
    driver = "com.mysql.jdbc.Driver";
    dbURL = "jdbc:mysql://localhost/BOOKINGSYSTEM";
    login = "root";
    password = "password";
    } catch(IOException e) {
    System.out.println("Error: Cannot laod configuration file ");
    }

    I have the following code which I do not understand
    the reason it is not work. i.e. Putting the driver,
    dbURL, login, password value in the beginning work,
    however, setting it in the try blocks does not. Can
    you please help me? Thank you.What exactly do you mean by "it does not work"?

  • 12.4 Beta C++ : Wrong warning  when using  outer try block.

    Following program
    int main(int argc, char ** argv) try {} catch(...) {}
    compiled with:
    CC t.cc +w
    gives
    "t.cc", line 1: Warning: argc hides the same name in an outer scope.
    "t.cc", line 1: Warning: argv hides the same name in an outer scope.
    int main(int argc, char ** argv)  { try {} catch(...) {} }
    does not give any warnings. )

    I always wonder how people are easily able to find bugs that we miss with our millions of tests.
    Thanks for reporting.
    18535152 - spurious hiding warning on function with func-try-block
    regards,
    __Fedor.

  • How to return a value with a try block?????????

    hi there
    if a method needs to return a value, but there maybe an exception caught in a try block, where should i place the return statement, outside the try bccok or inside
    code...
    public String readFrom()
    String temp;
    try
    temp = br.readLine();
    catch (IOException ex)
    System.out.println(ex);
    return temp;
    }

    It should be coded as you have it. There should (ideally)
    be only one exit point from a method. If an exception is
    thrown, the code in the catch block will be executed and
    processing will continue. You can use the catch block
    to set the value of the variable that is being returned to
    indicate that an error has occurred. In your example,
    you could set the String temp to null.
    Mark

  • OracleDataReader in a C# try-block ??

    There appears to be a chicken-hen problem with the OracleDataReader in a try-block in C#:
    Code like this:
    try
    OracleDataReader OraRdr = oraCmdAny1.ExecuteReader();
    OraRdr.Read();
    results in an CS0246 error saying the name OraRdr does not exist - and the C# documentation on the try-block explicitly warns about initalizing a variable inside a try-block.
    But how to resolve this as no constructor except the one above is available for the OracleDataReader ???
    Any thoughts?
    Michael

    Hi Michael,
    How about something like this?
    OracleDataReader OraRdr = null;
    try
      OraRdr = oraCmdAny1.ExecuteReader();
    catch (OracleException ex)
      OraRdr = null;
    if (OraRdr != null)
      OraRdr.Read();
    }Would that work for what you want to do?
    - Mark

Maybe you are looking for

  • Help I can only have max. 3 osx apps. open at the same time ?

    Help I can only have max. 3 apps. open at the same time ? If I have 3 apps. open, and try to open a 4th. this message comes up : The application "Mail" cannot be launched. -10810 Of cause if I'm trying to open up something else than mail, lets say iP

  • Validation on AP invoice

    Hi , Client requires validation on AP invoice if purchase invoice value is  greater than Purchase order value. For e.g. if purchase order is created for Item1 with 10 quantity and 100 price , total will be 1000 and purchase invoice is created as    

  • The Strange Case of Change Case

    My company's name is MCS.  When I'm writing in caps, and then I want to re-use that text in sentence case I use Indesign's change case feature to change caps to sentence case.  When ever my company's name is in the copy, I always have to go back and

  • Receiver does not work

    My phone's receiver doesn't work.This is factory error.Can I change?How much take?

  • Please help with the best way of adding together numbers like this ..

    Hey. What's the best way with J2ME to acheive this .. I have an integer, let's the it's value is "123456" and what I wanna do is to add them together this way: 1 + 2 +3 + 4 + 5 + 6. How would I do that? Thanks in advance!