Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Intro to Jython, Part 1: Java programming made easier

Barry Feigenbaum, Sr. Consulting IT Architect, IBM

Dr. Barry Feigenbaum is a member of the IBM Worldwide Accessibility Center, where he is part of team that helps IBM make its own products accessible to people with disabilities. Dr. Feigenbaum has published several books and articles, holds several patents, and has spoken at industry conferences such as JavaOne. He serves as an Adjunct Assistant Professor of Computer Science at the University of Texas, Austin.

Dr. Feigenbaum has more than 10 years of experience using object-oriented languages like C++, Smalltalk, the Java programming language, and Jython. He uses the Java language and Jython frequently in his work. Dr. Feigenbaum is a Sun Certified Java Programmer, Developer, and Architect.


Acknowledgements

I would like to acknowledge Mike Squillace and Roy Feigel for their excellent technical reviews of this tutorial.

Summary:  This is the first in a two-part tutorial that will introduce you to the Jython scripting language and provide you with enough knowledge to begin developing your own Jython-based applications. In this first half of the tutorial, you'll learn the concepts and programming basics of working with Jython, including access options and file compilation, syntax and data types, program structure, procedural statements, and functions.

Date:  08 Apr 2004
Level:  Introductory PDF:  A4 and Letter (1165 KB | 65 pages)Get Adobe® Reader®

Activity:  52334 views
Comments:  

Jython exceptions

About exceptions

Regardless of how much care a programmer takes in designing and testing his or her code, unexpected errors, or exceptions, can occur. Jython provides excellent support for recovering from these errors,

Exceptions are generally subclasses of the Jython type exceptions.Exception or the Java class java.lang.Exception. Most Jython exception names end in "Error" (such as IOError or IndexError) or "Warning." Java exceptions end in either "Error" (for critical exceptions) or "Exception" (for generally recoverable exceptions). For more information see The Jython exception hierarchy or the Python Library Reference (see Resources for a link).

The Jython exception hierarchy

Here is Jython's principle exception hierarchy subset.

  • 1 Exception
    • 1.1 SystemExit
    • 1.2 StopIteration
    • 1.3 StandardError
      • 1.3.1 KeyboardInterrupt
      • 1.3.2 ImportError
      • 1.3.3 EnvironmentError
        • 1.3.3.1 IOError
        • 1.3.3.2 OSError
      • 1.3.4 EOFError
      • 1.3.5 RuntimeError
        • 1.3.5.1 NotImplementedError
      • 1.3.6 NameError
        • 1.3.6.1 UnboundLocalError
      • 1.3.7 AttributeError
      • 1.3.8 SyntaxError
        • 1.3.8.1 IndentationError
        • 1.3.8.2 TabError
      • 1.3.9 TypeError
      • 1.3.10 AssertionError
      • 1.3.11 LookupError
        • 1.3.11.1 IndexError
        • 1.3.11.2 KeyError
      • 1.3.12 ArithmeticError
        • 1.3.12.1 OverflowError
        • 1.3.12.2 ZeroDivisionError
        • 1.3.12.3 FloatingPointError
      • 1.3.13 ValueError
      • 1.3.14 ReferenceError
      • 1.3.15 SystemError
      • 1.3.16 MemoryError
  • 2 Warning
    • 2.1 UserWarning
    • 2.2 DeprecationWarning
    • 2.3 PendingDeprecationWarning
    • 2.4 SyntaxWarning
    • 2.5 OverflowWarning
    • 2.6 RuntimeWarning
    • 2.7 FutureWarning

This hierarchy is a subset of the Python Library Reference (see Resources). These exceptions may be subclassed.


The try-except-else statement

Like C++ and the Java language, Jython supports exception handlers. These handlers are defined by the try-except-else statement, which has the following form:

try: statement
except type, var: statement
  :
else: statement

-- or --

try:
    block
except type, var:
    block
  :
else:
    block
                

The except clause may be repeated with different type values. If so, the exceptions either must not overlap hierarchically (that is, be siblings) or they must be ordered from child to root exceptions. The optional type value is an exception type (either a subclass of exceptions.Exception or java.lang.Throwable). If type is missing, then the except clause catches all Jython and Java exceptions. The optional var value receives the actual exception object. If var is missing, then the exception object is not directly accessible. The else clause is optional. It is executed only if no exception occurs.

If an exception occurs in the try clause, the clause is exited and the first matching except clause (if any) is entered. If no exception matches, the block containing the try-except-else is exited and the exception is re-raised.

If an exception is raised in the except or else clause, the clause will exit and the new exception will be processed in the containing block.


Accessing exception information

To access information about an exception, you may use the value provided in the except clause as described previously or the sys.exc_info function. For example, you can use the following function, in which type is the class of the exception, value is the exception object (use str(value) to get the message), and traceback is the execution trace back, which is a linked list of execution stack frames.

import sys
  :
try:
     :
except:
     type, value, traceback = sys.exc_info()

More details on the exceptions and trace backs is available in the Python Reference Manual (see Resources).


The try-finally statement

Like C++ and the Java language, Jython supports an additional construct, try-finally, which makes it easy to do required cleanup activities such as closing open files, releasing resources, etc. Any code in the finally clause is guaranteed to be executed once the try clause is entered, even if it is exited via a return statement (see The return statement) or an exception. The try-finally statement has the following forms:

try: statement
finally: statement

  -- or --

try:
    block
finally:
    block
                

Note that try-except-else statements may nest in try-finally statements and vice versa.


A try statement example

Here is an example of using both try-except and try-finally statements together. We'll talk more about Jython file I/O in Part 2 of this tutorial.

def readfile (name):
     "return the lines in a file or None if the file cannot be read"
     try:
         file = open(name, 'r')  # access the file
         try:
             return file.readlines()
         finally:
             file.close()    # ensure file is closed
     except IOError, ioe:    # report the error
         print "Exception -", ioe

:

# prints Exception - File not found - nofile (...)
# then None
print readfile("nofile")      

# prints a list of the lines in the file
print readfile("realfile")    



The raise statement

Exceptions are generated by called functions or built-in services. You can also generate one by using the raise statement. The raise statement has the following forms:

raise exception

  -- or --

raise exception_class {, message}

  -- or --

raise


Below are some example raise statements.

Example Comment(s)
raise Re-raise the current exception; used in an except block to regenerate the exception
raise IOError Create and raise an IOError with no message
raise anIOError Re-raise an existing IOError object
raise IOError, "End of File" Create and raise an IOError with a explanatory message
from java import io
raise io.IOException, "End of File"
Create and raise a Java exception with a explanatory message

9 of 16 | Previous | Next

Comments



Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=131933
TutorialTitle=Intro to Jython, Part 1: Java programming made easier
publish-date=04082004
author1-email=feigenba@us.ibm.com
author1-email-cc=jaloi@us.ibm.com

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).